Frage

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?

War es hilfreich?

Lösung

From MDN

The search() method executes a search for a match between a regular expression and this String 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(/\^/);

Andere Tipps

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("^");
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top