Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Search string error

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?

like image 656
lenikogotthis Avatar asked Aug 17 '26 03:08

lenikogotthis


1 Answers

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(/\^/);
like image 138
elclanrs Avatar answered Aug 18 '26 18:08

elclanrs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!