在javascript中的模式匹配

在下面的代码我没有得到正确的结果。 我怎样才能在JavaScript中做模式匹配?

function getPathValue(url, input) { console.log("this is path key :"+input); url = url.replace(/%7C/g, '|'); var inputarr = input.split("|"); if (inputarr.length > 1) input = '\\b' + inputarr[0] + '\n|' + inputarr[1] + '\\b'; else input = '\\b' + input + '\\b'; var field = url.search(input); var slash1 = url.indexOf("/", field); var slash2 = url.indexOf("/", slash1 + 1); if (slash2 == -1) slash2 = url.indexOf("?"); if (slash2 == -1) slash2 = url.length; console.log("this is path param value :"+url.substring(slash1 + 1, slash2)); return url.substring(slash1 + 1, slash2); } getPathValue("http://localhost/responsePath/mountainwithpassid|accesscode/100/mountainwithpassid|passid/1","mountainwithpassid|passid") 

我得到下面的输出

如果我通过mountainwithpassid |访问代码作为input我得到输出为100.同样的方式,如果我通过

关键:mountainwithpassid | passid
值:100 //预期输出1

如果您的目的是简单地检索input后面的path中的值(包含在'/'中),那么您可以用一个更简单的正则expression式来实现。 首先,你将需要一个方法来逃避你的inputstring,因为它包含一个pipe道字符'|' 在正则expression式中被翻译为OR。

你可以使用这个(取自https://stackoverflow.com/a/3561711 ):

 RegExp.escape= function(s) { return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'); }; 

那么你的getPathValue函数可以是这样的:

 function getPathValue(url, input) { var pathValue = null; var escapedInput = RegExp.escape(input); // The RegExp below extracts the value that follows the input and // is contained within '/' characters (the last '/' is optional) var pathValueRegExp = new RegExp(".*" + escapedInput + "/([^/]+)/?.*", 'g'); if (pathValueRegExp.test(url)) { pathValue = url.replace(pathValueRegExp, '$1'); } return pathValue; } 

您还需要考虑如何处理错误 – 在该示例中,如果找不到匹配项,则返回空值。

我试图理解这个问题。 给定一个URL:

 "http://localhost/responsePath/mountainwithpassid|accesscode/100/mountainwithpassid|passid/1" 

和一个论点:

 "mountainwithpassid|passid" 

您预期的回报值为:

 "1" 

一个论点

 "mountainwithpassid|accesscode" 

应该返回:

 "100" 

那是对的吗? 如果是这样(我不确定它是什么),那么以下内容可能适合:

 function getPathValue(url, s) { var x = url.indexOf(s); if (x != -1) { return url.substr(x).split('/')[1]; } } var url = "http://localhost/responsePath/mountainwithpassid|accesscode/100/mountainwithpassid|passid/1"; var x = "mountainwithpassid|passid"; var y = "mountainwithpassid|accesscode"; console.log(getPathValue(url, x)); // 1 console.log(getPathValue(url, y)); // 100