简体   繁体   中英

How to split a string after the nth occurence of a character?

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' ie, 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.

  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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM