簡體   English   中英

javascript:將字符串與占位符匹配

[英]javascript: match string with placeholders

我想檢查我的字符串“你好我的名字是托馬斯”是否與字符串“你好我的名字是$”匹配。 因此,對我來說,以下陳述應為真:

"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); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM