简体   繁体   中英

.split() at spaces and quotation marks, keep quotation marks - Regex/Javascript

I would like to return an array from a string. The array should contain all characters as separate elements, except for spaces. My current regex looks like this:

str = 'Stuff in "quotation marks"';
arr = str.split(/(?=["])|[\s+]/);
console.log(arr);
// [ 'Stuff', 'in', '"quotation', 'marks', '"' ]

I would like it to return something like this:

// [ 'Stuff', 'in', '"', 'quotation', 'marks', '"' ]

What regex can I use to return the " in front of '"quotation' as a separate element in the array?

You could use String.prototype.match() MDN

 const str = 'Stuff in "quotation marks"'; const arr = str.match(/\\w+|"/g); console.log(arr);

PS: Beware that \\w is analogous for [a-zA-Z0-9_]


You can also .split(/\\b/) at word boundaries /\\b/ but than trim and filter out empty values from the array:

 const str = 'Stuff in "quotation marks"'; const arr = str.split(/\\b/).map(w=>w.trim()).filter(w=>w); console.log(arr);

Disclaimer: the above examples will not work for special characters like š, ç, etc...

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