如何在Javascript中匹配相同的字符串?

时间:2019-01-07 10:44:59

标签: javascript arrays object

使用这两个网址:

Selenium::WebDriver::Error::ElementNotVisibleError: element not interactable
(Session info: chrome=71.0.3578.98)
(Driver info: chromedriver=2.43.600233 
(523efee95e3d68b8719b3a1c83051aa63aa6b10d),platform=Linux 4.15.0-43-generic x86_64)

是否有一种解决方案可以匹配这两个网址,并在它们相似时返回true?

我尝试了以下方法,应该是最糟糕的解决方案:

const url1 = '/user/{username}/edit'
const url2 = '/user/harry/edit'

编辑

解决方案是使用PathToRegExp包!感谢@ChiragRavindra!

2 个答案:

答案 0 :(得分:1)

您可以使用正则表达式测试网址

  • \/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));

答案 1 :(得分:-1)

我建议您看一下这个库 NPM - String similarity library

如果两个字符串相似,则库仅返回比较两个字符串的概率。 然后,您要根据您认为相同的百分比来设置阈值。

相关问题