在js中查找字符串中的字符“(”

find the character "(" in a string in js

我的 JS 中有一个字符串可能包含字符 (M,我需要找到它们的位置 - 但我无法在不抛出错误的情况下解决这个问题,我猜是因为括号。

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

尝试使用 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);

String.search 接受 Regular expression as its argument, but you're passing a string to it, so it doesn't work. Take a look at String.search() 以获取更多信息。

因此您的代码将如下所示:

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