Question

I am literally pulling my hair out on this one...

Here's the situation. I have two javascript strings as follows:

dsName = "Test 1"
replacementString = "Test "

I'm trying to see if dsName starts with replacementString, with the following code:

if(dsName.indexOf(replacementString) == 0)
{
    // I never get here!
}

indexOf is returning -1!! How is this possible? I can put a breakpoint in Chrome script debugging right before that line and paste "dsName.indexOf(replacementString)" into the console and see that it is indeed returning -1.

Now just to prove I'm not crazy I can from that same breakpoint print out dsName and it does in fact equal "Test 1" and replacementString does equal "Test ". Here is an actual screenshot from the Chrome debugging console:

enter image description here

So as you can see, if I paste in the literal string, it works as expected, but if I use the variable, it doesn't work. I've even tried String(replacementString) and replacementString.toString() to see if maybe it was a type issue, but it does the same thing.

It's like it works if the parameter for indexOf is a literal string, but not if it's a string variable.

Am I going crazy, is there a something stupid I'm missing? Or is this possibly a bug in Chrome?

Était-ce utile?

La solution 2

Kudos to Wolfgang for getting me on the right path to figuring this out, but it turned out to be something completely unexpected and different...

I was pulling the value of replacementText from a <textarea> which had a style of white-space:nowrap. I guess when nowrap is turned on, it returns spaces as non-breaking (ASCII code 160) and not as regular spaces.

Here's a js-fiddle to see what's going on: http://jsfiddle.net/Jk9Cw/

What do you guys think? Is this a "duh you've should have known" or a "wow, that is something I've never run into before"?

Autres conseils

It looks like some of the characters that look like spaces are not actually simple spaces. Try this to see what the string really contains:

for (var i=0; i<replacementString.length; i++) 
    console.log(replacementString.charCodeAt(i));

You can replace non-breaking spaces by regular ones like this:

replacementString = replacementString.replace(String.fromCharCode(160), " ");
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top