简体   繁体   中英

Split a text by quotes but not spaces in javascript

How can I split a given text by quotes only? For example:

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

would be split like:

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

Thanks for any help.

You may use match with alternation based regex:

 const str = 'He said "This is true", then added "Lets go"' var arr = str.match(/"[^"]*"|[^"]+/g); console.log(arr); 

Regex has 2 alternatives:

  • "[^"]*" : Match quotes strings
  • | : OR
  • [^"]+ : Match 1+ non-double-quote characters
    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]));
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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