javascript:匹配带占位符的字符串

javascript: match string with placeholders

我想检查我的字符串 "Hello my name is Thomas" 是否与字符串 "Hello my name is $" 匹配。 所以对我来说,以下陈述应该是正确的:

"Hello my name is Thomas" == "Hello my name is $"

之后我想提取 $ 字符串类似

function getParam(text, template) {
  returns "Thomas"
}

你有什么建议吗?

您可以创建一个正则表达式,然后使用 Regex.exec

检索数据

const regex = /Hello my name is (.*)/;

const ret = regex.exec('Hello my name is thomas');

console.log(ret[1]);


使用正则表达式时,可以使用https://regex101.com/。它可以帮助您了解自己在做什么。

您的例子:



function extractName(str) {
  const ret = /Hello my name is (.*)/.exec(str);

  return (ret && ret[1].trim()) || null;
}

const name = extractName('Hello my name is thomas');

const nameWithSpace = extractName('Hello my name is    thomas    ');

const fail = extractName('failure');

console.log(name);
console.log(nameWithSpace);
console.log(fail);