[英]Split string into array of characters, keep certain sequence together (JavaScript)
I have my string: 我有我的琴弦:
var str = '123\r\nabc';
Which I'd like to produce this array: 我想产生这个数组:
["1", "2", "3", "
", "a", "b", "c"]
So, I'm looking to split it by character, but to keep \\r\\n
together as one element in the resulting array. 因此,我希望按字符对其进行拆分,但要将
\\r\\n
在一起作为结果数组中的一个元素。
My failed attempts: 我失败的尝试:
console.log(str.split(/\r\n|/)); // removes \r\n
console.log(str.split(/\r\n/)); // splits by \r\n
You can't do this with split alone – /(\\r\\n)?/
, for example, would leave undefined
s in the result – so you'll need to resort to match
instead. 您不能单独使用split来执行此操作-例如,
/(\\r\\n)?/
会在结果中保留undefined
,因此您需要使用match
代替。
var result = str.match(/\r\n|[\S\s]/g);
where [\\S\\s]
is .
其中
[\\S\\s]
是.
but including newlines. 但包括换行符。 Note that
result
will be null
on an empty string. 请注意,在空字符串上
result
将为null
。
You can use this regex in split: 您可以在拆分中使用此正则表达式:
var str = "123\r\nabc";
console.log( str.split(/(\r\n)?/).filter(Boolean) );
\\r\\n
will make sure to capture it in the resulting array. \\r\\n
周围的捕获组将确保将其捕获到结果数组中。 filter(Boolean)
is used to filter out undefined elements from array. filter(Boolean)
用于从数组中过滤出未定义的元素。 Output: 输出:
["1", "2", "3", "
↵", "a", "b", "c"]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.