var str = 'single words "fixed string of words"'; var astr = str.split(" "); // need fix
I would like the array to be like this:
var astr = ["single", "words", "fixed string of words"];
In JavaScript, single (' ') and double (“ ”) quotes are frequently used for creating a string literal. Generally, there is no difference between using double or single quotes, as both of them represent a string in the end.
Use method String. split() It returns an array of String, splitted by the character you specified.
The split() method splits (divides) a string into two or more substrings depending on a splitter (or divider). The splitter can be a single character, another string, or a regular expression. After splitting the string into multiple substrings, the split() method puts them in an array and returns it.
Both single (' ') and double (" ") quotes are used to represent a string in Javascript. Choosing a quoting style is up to you and there is no special semantics for one style over the other. Nevertheless, it is important to note that there is no type for a single character in javascript, everything is always a string!
The accepted answer is not entirely correct. It separates on non-space characters like . and - and leaves the quotes in the results. The better way to do this so that it excludes the quotes is with capturing groups, like such:
//The parenthesis in the regex creates a captured group within the quotes var myRegexp = /[^\s"]+|"([^"]*)"/gi; var myString = 'single words "fixed string of words"'; var myArray = []; do { //Each call to exec returns the next regex match as an array var match = myRegexp.exec(myString); if (match != null) { //Index 1 in the array is the captured group if it exists //Index 0 is the matched text, which we use if no captured group exists myArray.push(match[1] ? match[1] : match[0]); } } while (match != null);
myArray will now contain exactly what the OP asked for:
single,words,fixed string of words
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With