简体   繁体   English

第n个字符出现后如何拆分字符串?

[英]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)'; 我有一个字符串,需要在javascript中拆分var str ='Lenovo Essential G500s(59-388254)笔记本电脑(第三代Ci5 / 8GB / 1TB / DOS / 2GB图)(免费随身携带的包)(黑色)';

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. 我只需要检索“ Lenovo Essential G500s(59-388254)笔记本电脑”,即,我应该能够在第二次出现“(”字符后拆分字符串。

I have tried using the .split() function, but I am not able to specify the position. 我尝试使用.split()函数,但无法指定位置。 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? 有关更通用的解决方案,请参见现有答案: 如何获取字符串中的第n个出现的字符?

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 干杯

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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