Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript split string on space or on quotes to array

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"]; 
like image 507
Remi Avatar asked May 12 '10 09:05

Remi


People also ask

Is it better to use single or double quotes in JavaScript?

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.

How do you split a string with double quotes?

Use method String. split() It returns an array of String, splitted by the character you specified.

Can you use split on an array?

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.

What is the difference between single quotation and double quotation in JavaScript?

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!


1 Answers

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 
like image 111
dallin Avatar answered Sep 21 '22 08:09

dallin