最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to split a string after the nth occurence of a character? - Stack Overflow

programmeradmin2浏览0评论

I have a string which i need to split in javascript var str = 'Lenovo Essential G500s (59-388254) Laptop (3rd Gen Ci5/ 8GB/ 1TB/ DOS/ 2GB Graph) (Free carry bag) (Black)';

I need to retrieve just 'Lenovo Essential G500s (59-388254) Laptop' i.e, i should be able to split the string after the second occurrence of '(' character.

I have tried using the .split() function, but I am not able to specify the position. Please help.

I have a string which i need to split in javascript var str = 'Lenovo Essential G500s (59-388254) Laptop (3rd Gen Ci5/ 8GB/ 1TB/ DOS/ 2GB Graph) (Free carry bag) (Black)';

I need to retrieve just 'Lenovo Essential G500s (59-388254) Laptop' i.e, i should be able to split the string after the second occurrence of '(' character.

I have tried using the .split() function, but I am not able to specify the position. Please help.

Share Improve this question edited Oct 10, 2013 at 11:00 Boaz 20.2k9 gold badges66 silver badges72 bronze badges asked Oct 10, 2013 at 10:56 user2866631user2866631 731 silver badge7 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4
  var str = 'Lenovo Essential G500s (59-388254) Laptop (3rd Gen Ci5/ 8GB/ 1TB/ DOS/ 2GB Graph) (Free carry bag) (Black)';

  var firstBracket = str.indexOf('(');
  var secondBracket = str.indexOf('(', firstBracket+1)
  str.substring(0, secondBracket);

This will give you the section you're looking for.

For a more general solution, see the existing answer: How to get the nth occurrence in a string?

try this:

var str = 'Lenovo Essential G500s (59-388254) Laptop (3rd Gen Ci5/ 8GB/ 1TB/ DOS/ 2GB Graph) (Free carry bag) (Black)';

var index =  str.indexOf(")");

var res = str.substring(0, index +1);

alert(res);

Cheers

发布评论

评论列表(0)

  1. 暂无评论