3

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?

4 Answers 4

2

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(/\^/);
Sign up to request clarification or add additional context in comments.

Comments

2

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>

Comments

2

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

Comments

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("^");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.