If I have three and more hyphens in string I need to get from the string substring after second hyphen.
For example, I have this string:
"someStr1 - someStr2 - someStr3 - someStr4"
As you can see it has 3 hyphens, I need to get from string above substring:
"someStr3 - someStr4"
I know that I need to get the index position of second hyphen and then I can use substring function But I don't know how to check if there is more then 3 hyphens and how to check thet position is of the second hyphen.
If I have three and more hyphens in string I need to get from the string substring after second hyphen.
For example, I have this string:
"someStr1 - someStr2 - someStr3 - someStr4"
As you can see it has 3 hyphens, I need to get from string above substring:
"someStr3 - someStr4"
I know that I need to get the index position of second hyphen and then I can use substring function But I don't know how to check if there is more then 3 hyphens and how to check thet position is of the second hyphen.
Share Improve this question asked Apr 17, 2018 at 12:38 MichaelMichael 13.6k59 gold badges170 silver badges315 bronze badges 1- 2 please show what you have tried to do. What was the result? – depperm Commented Apr 17, 2018 at 12:40
3 Answers
Reset to default 6You can use the RegEx (?<=([^-]*-){2}).*
(?<=([^-]*-){2})
makes sure there is 2-
before your match(?<= ... )
is a positive lookbehind[^-]*
matches anything but a-
, 0 or more times-
matches-
literally
.*
matches anything after those 2 dashes.
Demo.
const data = "someStr1 - someStr2 - someStr3 - someStr4";
console.log(/(?<=([^-]*-){2}).*/.exec(data)[0]);
Split string to array with -
and check if array.length > 3
which means at least three -
in the string. If true, join the array from index == 2
to the end with -
and trim the string.
var text = "someStr1 - someStr2 - someStr3 - someStr4"
var textArray = text.split('-')
if(textArray.length>3){
console.log(textArray.slice(2).join('-').trim())
}
How about something like this:
var testStr = "someStr1 - someStr2 - someStr3 - someStr4";
var hyphenCount = testStr.match(/-/g).length;
if(hyphenCount > 2){
var reqStr = testStr.split('-').slice(-2).join('-');
console.log(reqStr) // logs "someStr3 - someStr4"
}
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744354895a4570182.html
评论列表(0条)