ajsie
ajsie

Reputation: 79696

Advanced JavaScript split

I have to split this string here in JavaScript:

 hl=windows xp \"windows xp\"

to three words.

I used:

 keywords = keywords.split(/ /);

But then i got 4 words:

windows
xp
\"windows
xp\"

How could i split this string to just 3 words?

EDIT: and how do i remove the \".

Upvotes: 1

Views: 1480

Answers (3)

sworoc
sworoc

Reputation: 1461

hl="windows xp \"windows xp\""

var results = hl.split(/ /);

for(var s in results) {
    try {
        while (results[s].search("\"") > -1) {
            results.splice(s, 1);
        }
    } catch(e) {}
}

var quoted = hl.match(/"[^"]*"/g); //matches quoted strings

for(var s in quoted) {
    results.push(quoted[s]);
}

//results = ["windows", "xp", ""windows xp""]

edit, a one liner:

var results = hl.match(/\w+|"[^"]*"/g).map(function(s) {
    return s.replace(/^"+|"+$/g, "")
});

Upvotes: 2

Gumbo
Gumbo

Reputation: 655269

Here’s a simple one:

keywords = keywords.match(/"[^"]*"|\w+/g).map(function(val) {
    if (val.charAt(0) == '"' && val.charAt(val.lenngth-1) == '"') {
        val = val.substr(1, val.length-2);
    }
    return val;
});

Upvotes: 2

barkmadley
barkmadley

Reputation: 5297

function split(s, on) {
    var words = [];
    var word = "";
    var instring = false;
    for (var i = 0; i < s.length; i++) {
        var c = s.charAt(i);
        if (c == on && !instring) {
            words.push(word);
            word = "";
        } else {
            if (c != '"')
                word += c;
        }
        if (c == '"') instring = !instring;
    }
    if (word != '') words.push(word); //dangling word problem solved
    return words;
}

and a usage example that fits the OP's example

var hl = "windows xp \"windows xp\"";
split(hl, " "); // returns ["windows","xp","windows xp"]

Upvotes: 2

Related Questions