Skip to content Skip to sidebar Skip to footer

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

Solution 1:

  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?

Solution 2:

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

Post a Comment for "How To Split A String After The Nth Occurence Of A Character?"