Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected result from String.indexOf function?

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?

like image 439
Jim Heising Avatar asked Mar 11 '26 22:03

Jim Heising


1 Answers

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), " ");
like image 196
Wolfgang Stengel Avatar answered Mar 14 '26 11:03

Wolfgang Stengel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!