String.indexOf函数的意外结果? [英] Unexpected result from String.indexOf function?

查看:64
本文介绍了String.indexOf函数的意外结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从字面上看,我正在拔头发...

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

这是情况.我有两个JavaScript字符串,如下所示:

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

dsName = "Test 1"
replacementString = "Test "

我正在尝试使用以下代码查看dsName是否以replaceString开头:

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

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

indexOf返回-1!这怎么可能?我可以在该行之前在Chrome脚本调试中放置一个断点,然后将"dsName.indexOf(replacementString)"粘贴到控制台中,看看它确实返回-1.

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.

现在只是为了证明我不是疯子,我可以从同一个断点打印出dsName,它实际上等于"Test 1",而replacementString等于"Test".这是Chrome调试控制台中的实际屏幕截图:

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:

因此,如您所见,如果我粘贴文字字符串,它会按预期工作,但是如果使用变量,它将无法工作.我什至尝试过String(replacementString)和replaceString.toString()来查看是否可能是类型问题,但是它做同样的事情.

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.

如果indexOf的参数是文字字符串,就好了,但是如果它是字符串变量,就好了.

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

我疯了吗,我有什么愚蠢的东西想念吗?还是这可能是Chrome中的错误?

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

推荐答案

Wolfgang为使我走上正确的道路而对他表示敬意,但事实证明这完全是出乎意料且与众不同的……

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...

我从具有 white-space:nowrap 样式的< textarea> 中提取了replaceText的值.我猜想当nowrap打开时,它会以不间断(ASCII代码160)而不是常规空格的形式返回空格.

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.

这里是一个js小提琴,以查看发生了什么事情: http://jsfiddle.net/Jk9Cw/

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

这篇关于String.indexOf函数的意外结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆