我目前正在用 JavaScript 编写一个短程序,该程序匹配字符串中的子字符串,中间有一个通配符。
let string1 = "The man is outside.";
let string2 = "I have two minutes.";
let string3 = "The men are here.";
我试图找到一个包含“m_n”的正则表达式。
我一直在尝试使用以下功能:
let matching = function(string) {
if (string.match(^m.*n$)) {
console.log("it does");
}
else {
console.log("it doesnt");
}
}
但我不断收到错误“SyntaxError: Unexpected token ^”。
有没有人有任何指点?
最佳答案
问题是您忘记分配/(正斜杠)。 我建议在 if 语句中使用 test 而不是 match。
let string = "msdfsxn";
if (/^m.*n$/.test(string)) {
console.log("it does");
} else {
console.log("it doesn't");
}
关于javascript - 使用 VCS 在 JavaScript 中匹配子字符串的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57967138/