简体   繁体   English

如何在 JavaScript 中获取特定字符串

[英]How to get a specific string in JavaScript

I have:我有:

var text = 'LTE CSSR (East xr) (301-LT_King_St_PC)'

and I want to split from (East xr) (301-LT_King_St_PC) only as follow:我只想从(East xr) (301-LT_King_St_PC)拆分如下:

var result = text.split('(')
result = (East xr) (301-LT_King_St_PC)

You can use a regular expression with the match function to get this done.您可以使用match function 的正则表达式来完成此操作。 Depending on how you want the result try one of the following:根据您想要的结果,尝试以下方法之一:

 var text = 'LTE CSSR (East xr) (301-LT_King_St_PC)' console.log('one string:', text.match(/\(.*\)/)[0]) console.log('array of strings:', text.match(/\([^\)]*\)/g))

The first does what you seem to be asking for - a single output of everything between the first ( and the second ).第一个执行您似乎要求的操作-第一个(和第二个)之间的所有内容的单个 output 。 It does this by searching for /\(.*\)/ which is a regex that says "everything in between the parentheses".它通过搜索/\(.*\)/来做到这一点,这是一个表示“括号之间的所有内容”的正则表达式。

The second match splits it into all parenthesised strings using /\([^\)]*\)/g which is a regex that says "each parenthesised string" but the g at the end says "all of those" so an array of each is given.第二个match使用/\([^\)]*\)/g将其拆分为所有带括号的字符串,这是一个正则表达式,表示“每个带括号的字符串”,但最后的g表示“所有这些”,因此数组每个都给出。

You can do it using substring() and indexOf() :您可以使用substring()indexOf()来做到这一点:

 var text = 'LTE CSSR (East xr) (301-LT_King_St_PC)'; var result = text.substring(text.indexOf('(')); console.log(result);

You're quite close with your current method.您与当前方法非常接近。 One way you could try this is to use multiple characters within your split您可以尝试的一种方法是在拆分中使用多个字符

var result = text.split(") (") 
# Output -> result = ["(East xr", "301-LT_King_St_PC)"]

From here, some string manipulation could get rid of the brackets.从这里开始,一些字符串操作可以摆脱括号。

Alternatively you can also use String.match and join its result:或者,您也可以使用String.match并加入其结果:

 const text = 'LTE CSSR (East xr) (301-LT_King_St_PC)'; const cleaned = text.match(/\(.+[^\)]\)/).join(` `); console.log(cleaned);

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

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