[英]How to match identical strings in Javascript?
采取以下兩個網址:
const url1 = '/user/{username}/edit'
const url2 = '/user/harry/edit'
是否有解決方案來匹配這兩個URL並在它們相似時返回true?
我嘗試了以下方法,應該是最糟糕的解決方案:
const url1 = '/user/{username}/edit'
const url2 = '/user/harry/edit'
const split1 = url1.split('/')
const split2 = url2.split('/')
let matchCount = 0
let notMatchedCount = 0
split1.map(x => {
if(x === split2[x]) {
matchCount++
} else {
notMatchedCount++
}
})
if(matchCount > notMatchedCount) {
console.log('Match Found')
} else {
console.log('Match not found')
}
解決方法是使用PathToRegExp包! 感謝@ChiragRavindra!
您可以使用正則表達式測試網址
\\/user\\/
匹配/user/
\\w+
匹配1個或多個單詞字符( [a-zA-Z0-9_]+
) \\/edit
匹配項/edit
const url1 = '/user/{username}/edit'; const urlCorrect = '/user/harry/edit'; const urlWrong = '/users/harry/edit'; //generate a regex string by escaping the slashes and changing word between curly brackets with {\\w+} var regexString = url1.replace(/\\{\\w+\\}/g, '\\\\w+').replace(/\\//g, '\\\\/'); console.log('generating regex: ' + regexString); var regex = new RegExp(regexString); //test using the generated regex console.log(regex.test(urlCorrect)); console.log(regex.test(urlWrong));
我建議您查看此庫NPM-字符串相似度庫
如果兩個字符串相似,則庫僅返回比較兩個字符串的概率。 然后,您要根據您認為相同的百分比來設置閾值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.