用引号分隔文本,而不用javascript分隔空格

时间:2019-02-28 11:05:47

标签: javascript regex

如何仅用引号分隔给定文本?例如:

'He said "This is true", then added "Lets go"'

将被分割为:

['He said', '"This is true"', ', then added', '"Lets go"']

感谢您的帮助。

2 个答案:

答案 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]));
    }