javascript - How to get from the string substring after second hyphen? - Stack Overflow

If I have three and more hyphens in string I need to get from the string substring after 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.

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
Add a ment  | 

3 Answers 3

Reset to default 6

You 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条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信