admin管理员组文章数量:1420119
My problem is with the javascript search string function. I'm not able to find the symbol "^" in my string. For example:
string = "2^3";
n = string.search("^");
console.log(n);
With this example it would log i = "0". But the "^" is in "1". This works with any other search than caret ('^').
Can anyone help me fix this?
My problem is with the javascript search string function. I'm not able to find the symbol "^" in my string. For example:
string = "2^3";
n = string.search("^");
console.log(n);
With this example it would log i = "0". But the "^" is in "1". This works with any other search than caret ('^').
Can anyone help me fix this?
Share Improve this question asked Jan 20, 2014 at 7:27 lenikogotthislenikogotthis 335 bronze badges4 Answers
Reset to default 2From MDN
The
search()
method executes a search for a match between a regular expression and thisString
object.
str.search(regexp)
So it expects a regex. ^
is a regex special character. You need to escape it:
n = string.search("\\^");
Or simply use a regex:
n = string.search(/\^/);
it wants a regex. strings without special characters in them look the same as a regex, but that isn't the case when there are special characters.
<script>
string = "2^3";
n = string.search(/\^/);
console.log(n); //1
</script>
As per the String.prototype.search
docs, the first parameter passed will be treated as a Regular Expression.
regexp
A regular expression object. If a non-RegExp object obj is passed, it is implicitly converted to a RegExp by using new RegExp(obj).
So, the string you are passing, is converted to a RegExp
object and ^
in Regular expression, means that the first character. So, it returns the index of the first character, 0
.
You actually have to escape ^
like this \\^
var inputString = "2^3";
var n = inputString.search("\\^");
console.log(n);
Output
1
Why your code doesn't work has already been explained by other answers. Yet the simplest solution is missing: Use .indexOf
instead of .search
:
var n = inputString.indexOf("^");
本文标签: JavaScript Search string errorStack Overflow
版权声明:本文标题:JavaScript Search string error - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745327064a2653641.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论