如何仅用引号分隔给定文本?例如:
'He said "This is true", then added "Lets go"'
将被分割为:
['He said', '"This is true"', ', then added', '"Lets go"']
感谢您的帮助。
答案 0 :(得分:2)
您可以将match
与基于交替的正则表达式一起使用:
const str = 'He said "This is true", then added "Lets go"'
var arr = str.match(/"[^"]*"|[^"]+/g);
console.log(arr);
正则表达式有两种选择:
"[^"]*"
:匹配引号字符串|
:或[^"]+
:匹配1个以上非双引号字符答案 1 :(得分:0)
var text = 'He said "This is true", then added "Lets go"';
var indexes = [];
for (var i = 0; i < text.length; i++) {
if (text[i] === '"') indexes.push(i);
}
var array = [];
array.push(text.substring(0, indexes[0] + 1));
for (var i = 0; i < indexes.length; i++) {
array.push(text.substring(indexes[i], indexes[i + 1]));
}