void
void

Reputation: 36703

.split() working weird on some strings

I am trying to split a string with spaces on the keypress of a contenteditable div. But the split is working very wierdly.

Just try to run the below code once:

var d = "mod india jned cjkdem demdjkjncj kdeknd kmdke kmdekmd".split(" ");
document.getElementById("result").innerHTML = JSON.stringify(d);
<div id="result"></div>

The expected output should be an array of all the words.

Upvotes: 1

Views: 152

Answers (1)

trincot
trincot

Reputation: 351369

You have some white space characters that are not normal spaces (but non-breaking spaces). To catch them also, use the regular expression /\s/, like so:

var d = "mod india jned cjkdem demdjkjncj kdeknd kmdke kmdekmd".split(/\s/);
document.getElementById("result").innerHTML = JSON.stringify(d);
<div id="result"></div>

Here is how you can see which white space characters you have, using charCodeAt(0):

var d = "mod india jned cjkdem demdjkjncj kdeknd kmdke kmdekmd".match(/\s/g)
       .map(ch => ch.charCodeAt(0));
document.getElementById("result").innerHTML = JSON.stringify(d);
<div id="result"></div>

The code 32 represents the normal space, while 160 is the code of a non-breaking space.

Upvotes: 8

Related Questions