简体   繁体   English

如何根据[]将字符串拆分为数组?

[英]How to split a string into array based on []?

I am trying to split a string into an array of words that is present within [].我正在尝试将字符串拆分为 [] 中存在的单词数组。 Consider I have a string stating =>假设我有一个字符串 =>

const savedString = '[@hello hello] [@Bye bye], [@Friends forever] will miss you.'

Now I want to break the string into an array that will only contain.现在我想把字符串分解成一个只包含的数组。

const requiredArray = ['hello hello', 'Bye bye', 'Friends forever'];

I know about the split(), but only one delimiter can be passed.我知道 split(),但只能传递一个定界符。 Need help.需要帮忙。

https://www.w3schools.com/jsref/jsref_split.asp https://www.w3schools.com/jsref/jsref_split.asp

You can use .match() method with a regular expression with lookahead and lookbehind:您可以将.match()方法与具有先行和后行的正则表达式一起使用:

 const savedString = '[@hello] [@Bye], [@Friends] will miss you.' const n = savedString.match(/(?<=\[@)[^\]]*(?=\])/g); console.log( n );

What of [@hello hell[@Bye bye] => Bye bye [@hello hell[@Bye bye] => Bye bye

If say for example the string is: '[@hello] [@Bye], [@Friends] will miss you [@hello hell[@Bye bye].'例如,如果字符串是: '[@hello] [@Bye], [@Friends] will miss you [@hello hell[@Bye bye].'

One approach would be add to the above solution map() so each element is .split() at [@ and call pop() on the resulting array:一种方法将添加到上述解决方案map()中,因此每个元素都是.split() at [@并在结果数组上调用pop()

//starting with [ "hello", "Bye", "Friends", "hello hell[@Bye bye" ]
.map(word => 
    //split word into array
    word.split('[@')
    //[ ["hello"], ["Bye"], ["Friends"], ["hello hell", "Bye bye"] ]
    //Now take the last element
    .pop()
)
//Result: [ "hello", "Bye", "Friends", "Bye bye" ]

DEMO演示

 const savedString = '[@hello] [@Bye], [@Friends] will miss you [@hello hell[@Bye bye].'; const n = savedString.match(/(?<=\[@)[^\]]*(?=\])/g).map(w => w.split('[@').pop()); console.log( n );

Note: Just so that you do not run into errors whenever there's no match, consider changing:注意:为了避免在没有匹配项时出现错误,请考虑更改:

 savedString.match(/(?<=\[@)[^\]]*(?=\])/g)`

To:到:

(savedString.match(/(?<=\[@)[^\]]*(?=\])/g) || [])

You can achieve this with regex.您可以使用正则表达式实现此目的。

 const savedString = '[@hello] [@Bye], [@Friends] will miss you.'; const regex = /\[@([a-zA-Z]+)\]/g; const matches = savedString.match(regex); const result = matches.map(match => match.replace(/\[@|\]/g, '')); console.log(result);

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

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