Unexpected result from String.indexOf function?

▼魔方 西西 提交于 2019-12-14 01:29:49

问题


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:

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?


回答1:


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), " ");



回答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"?



来源:https://stackoverflow.com/questions/21195583/unexpected-result-from-string-indexof-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!