正则表达式不工作删除字符串/什么

时间:2016-06-23 09:54:29

标签: javascript

如何从href中删除此字符串并更新它?

示例网址:

"localhost:21088/WcfDataService1.svc/Clients?$top=20&$select=Name,Products/Name,ID,People/FirstName,Products/Price,People/LastName&$expand=People"

我在尝试什么:

var stringToRemove = "Products" + "/";
var url = $("#qUrl").attr("href");
url = url.replace('/(' + stringToRemove + '\/\w+,)/g', '');
$("#qUrl").attr("href", url);

我想要的是什么:

"localhost:21088/WcfDataService1.svc/Clients?$top=20&$select=Name,ID,People/FirstName,People/LastName&$expand=People"

更新

请不要硬编码

2 个答案:

答案 0 :(得分:1)

如果您要删除所有Products/...,而不是RegEx /Products\/.*?,/g

请注意,RegExp按编写 - 不用引号括起来。



var str = 'localhost:21088/WcfDataService1.svc/Clients?$top=20&$select=Name,Products/Name,ID,People/FirstName,Products/Price,People/LastName&$expand=People';

console.log(str.replace(/Products\/\w+,?/g, ''));

/**
 * Replace with variable string
 */

var key = 'Products'; // Come from external source, not hardcoded.
var pattern = new RegExp(key+'/\\w+,?', 'g'); // Without start and end delimiters!
console.log(str.replace(pattern, ''));




答案 1 :(得分:0)

 var stringToRemove = "Products" + "/";
 var url = $("#qUrl").attr("href");
url = url.replace(/Products\/Name,/g, '');
 $("#qUrl").attr("href", url);

修改替换呼叫,使用不带引号的正则表达式