Home > OS >  find the character "(" in a string in js
find the character "(" in a string in js

Time:01-30

I have a string in my JS that may contain the character (M and I need to find their position - but I can't work out how to without throwing an error I guess due to the bracket.

const findMTag = "(M"; //I need to search for this but it throws an error
let posMTag = nameJoined.search(findMTag);
console.log("TAG position =  "   posMTag);

CodePudding user response:

String.search accepts a Regular expression as its argument, but you're passing a string to it, so it doesn't work. Take a look at String.search() for more info.

So your code will look like:

const findMTag = /\(M/;
const posMTag = nameJoined.search(findMTag);
console.log("TAG position =  "   posMTag);

CodePudding user response:

Try with indexOf

const findMTag = "(M"; //I need to search for this but it throws an error
let posMTag = nameJoined.indexOf(findMTag);
console.log("TAG position =  "   posMTag);
  •  Tags:  
  • Related