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?
Use method String. split() It returns an array of String, splitted by the character you specified.
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.
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."
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.
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"']
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