Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string into words with whitespace unless in between a pair of double quotation marks

I want to split this string:

get "something" from "any site"

to array. I've done that:

var array = $(this).val().replace(/\s+/g, ' ').split(" ");

But I don't want to split words in quotation marks ("").

whether it can be done in a simple way?

like image 562
Piotrek Avatar asked Sep 09 '13 17:09

Piotrek


People also ask

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.

How do you split a string with white space characters?

You can split a String by whitespaces or tabs in Java by using the split() method of java. lang. String class. This method accepts a regular expression and you can pass a regex matching with whitespace to split the String where words are separated by spaces.

What is a string within quotation marks called?

A series of characters enclosed in matching quotation marks is called a literal string. The following examples both contain literal strings. SAY 'This is a REXX literal string.' /* Using single quotes */ SAY "This is a REXX literal string."

How do you split quotation marks?

A quote can be split by the attribution – the who said. You have to decide whether the 2nd half is a full sentence or not. If the 2nd half is a continuation of the quote, then don't use a capital. If the 2nd half is a sentence by itself, then use a capital.


1 Answers

A solution :

var str = 'get "something" from "any site"';
var tokens = [].concat.apply([], str.split('"').map(function(v,i){
   return i%2 ? v : v.split(' ')
})).filter(Boolean);

Result :

["get", "something", "from", "any site"]

It's probably possible to do simpler. The idea here is to split using " and then split by the space the odd results of the first splitting.

If you want to keep the quotes, you may use

var tokens = [].concat.apply([], str.split('"').map(function(v,i){
     return i%2 ? '"'+v+'"' : v.split(' ')
})).filter(Boolean);

Result :

['get', '"something"', 'from', '"any site"']
like image 173
Denys Séguret Avatar answered Oct 21 '22 11:10

Denys Séguret