[英]How to capture a string from the parameters of a url using regex expressions in javascript
我有一个功能可以显示用户访问的网址,例如https://stackoverflow.com/questions/78/of/103/uk/ask
我想将正则表达式与javascript配合使用以捕获url的特定参数,并将其替换为占位符文本。 以上面的例子为例;
当https://stackoverflow.com/questions/7845w98439/uk/ask匹配时,将'/ 78 / of / 103 / uk /'部分替换为'/ task / of / total / country /'。 我下面的代码似乎不起作用。 有人可以告诉我我要去哪里了吗?
JS:
const url_change = [
{expression: '/^/78/of/103/uk//i', value: '/task/of/total/country/'}
];
const urlParam = url_change.reduce(function(result, item) {
return element.classList.contains(item.expression) ? item.value : result;
}, '');
return urlParam(
toChange ? toChange.value : getElementText(element)
);
请按照以下步骤进行:
var str = "https://stackoverflow.com/questions/78/of/103/uk/ask"; const url_change = [ {expression: /\\/78\\/of\\/103\\/uk\\//i, value: '/task/of/total/country/'} ]; // console.log(url_change[0].expression.test(str)); var result = str.replace(url_change[0].expression,url_change[0].value); console.log(result);
符号/
是特殊字符(宣布Regex表达式的末尾),它需要一个标记\\
导致成为/
的url,用于Regex表达式!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.