【问题标题】:javascript: match string with placeholdersjavascript:将字符串与占位符匹配
【发布时间】:2019-04-08 16:41:54
【问题描述】:

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

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

之后我想提取 $ 字符串之类的东西

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

你有什么建议吗?

【问题讨论】:

  • 向我们展示您的尝试。

标签: javascript regex placeholder


【解决方案1】:

您可以创建一个正则表达式,然后使用 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);

【讨论】:

  • 当未找到匹配项时,该函数应更好地返回 null 而不是 false - 使其更适合 IMO。
  • @Sнаđошƒаӽ 为什么不 :) 重要的是它不是字符串
  • 因为exec 在找不到匹配项时返回null 本身。我会使用警卫提前归还它,然后继续处理比赛。 if (!ret) return ret;但这只是个人喜好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-21
  • 1970-01-01
  • 2018-10-21
  • 1970-01-01
  • 2016-09-24
  • 1970-01-01
相关资源
最近更新 更多