[英]javascript: match string with placeholders
I want to check if my string "Hello my name is Thomas" matches with the string "Hello my name is $". 我想检查我的字符串“你好我的名字是托马斯”是否与字符串“你好我的名字是$”匹配。 So for me following statement should be true:
因此,对我来说,以下陈述应为真:
"Hello my name is Thomas" == "Hello my name is $"
afterwards i want to extract the $ string something like 之后,我想提取$字符串像
function getParam(text, template) {
returns "Thomas"
}
Do you have any suggestions? 你有什么建议吗?
You can create a regex, then retrieve the data using Regex.exec
您可以创建一个正则表达式,然后使用
Regex.exec
检索数据。
const regex = /Hello my name is (.*)/; const ret = regex.exec('Hello my name is thomas'); console.log(ret[1]);
When using regex, you can use of https://regex101.com/ . 使用正则表达式时,可以使用https://regex101.com/ 。 it helps you understand what you are doing.
它可以帮助您了解自己在做什么。
Example in your case : 您的示例:
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.