javascript - Limited splits without losing the rest of the string? -
say have:
var str = "this string separated spaces";
and did:
alert(str.split(" " , 1));
the outcome "this"
whereas want outcome "this,is string separated spaces"
maybe split isn't right method?
what i'm trying separate string parts based on semicolons, unless semicolons in quotes. example, want
randomnessstuff;morestuff;some more stuff
to in 3 parts, i've been doing:
var str = "randomnessstuff;morestuff;some more stuff"; var parts = str.split(";");
which has been working fine, if semicolon in quotes, want not separated part.
for example, with:
var str = "randomnessstuff;morestuff , semicolon in quotes : ";";some more stuff";
i want part 1 randomnessstuff
, part 2 morestuff , semicolon in quotes : ";"
, , part 3 some more stuff
of course, if did split semicolon again, make part 3 quote.
what i'm hoping have loop checks semicolons 1 one see if they're in quotes, , if not, split them. if last bit didn't make sense, please answer first question, using split without losing rest of string.
the easy way 1 unfortunately manual.
var r = "randomnessstuff;morestuff , semicolon in quotes : \";\";some more stuff" var l = r.length var out = [] var inquotes = false; function togglequotes(){ inquotes = !inquotes } var tmp = "" for(var = 0; < l; i++ ) { // examine character character. var chr = r.charat(i); // handles 1 type of quote , no escapes if( chr == '"' ) togglequotes(); /* escape might this: if( chr == '"' && r.charat(i-1) != '\' ) support both types of quotes might be: if( chr == '"' || chr == "'" && r.charat(i-1) != '\' ) togglequotes(chr); togglequotes be: function togglequotes(chr){ if(inquotes == chr) inquotes = false; else inquotes = chr } */ if( !inquotes && chr == ";" ) { out.push(tmp); // store temp string tmp = "" // reset strubg } else tmp += chr // append temporary string } out.push(tmp) // remainder needs added still. console.log(out) //["randomnessstuff", // "morestuff , semicolon in quotes : ";"", // "some more stuff"]
Comments
Post a Comment