简体   繁体   English

在每次出现字符时拆分字符串,但将字符保留在新数组中

[英]Split string at every occurrence of character, but keep character in new array

If I have a string which looks like this:如果我有一个看起来像这样的字符串:

 let oldString = '[foo faa] [faaaa] [feee foo] [fu]';

How can I split it to return the following:如何拆分它以返回以下内容:

let newArr = ['[foo faa]','[faaaa]','[feee foo]','[fu]'];

So I would like to split it at every ']' character, but keep to that character in the new array.所以我想在每个 ']' 字符处拆分它,但在新数组中保留该字符。

I've tried oldString.split(']') but it does not return the array in the shape I was expecting.我试过oldString.split(']')但它没有返回我期望的形状的数组。

You could match the parts with the left and right delimiter.您可以将部分与左右分隔符匹配。

 let string = '[foo bar] [faaaa] [feee] [fu]', array = string.match(/\[[^\]]+\]/g); console.log(array);

You can find the answer below.您可以在下面找到答案。

 let oldString = '[foo faa] [faaaa] [feee foo] [fu]'; let newStringArr = oldString.split(" ").join(',').replace(/\],\[/gi, "],d[").split(",d") console.log(newStringArr); document.write(JSON.stringify(newStringArr))

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

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