Mathematics
Mathematics

Reputation: 7618

Regex not working to remove string/whatever

How can I remove this string from href and update it ?

Example Url:

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

What I am trying:

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

What I want:

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

Update

Please don't hard code

Upvotes: 1

Views: 61

Answers (2)

Justinas
Justinas

Reputation: 43441

If you are looking to remove all Products/..., than RegEx is /Products\/.*?,/g

Take a note that RegExp is written as is - without surrounding it with quotes.

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, ''));

Upvotes: 1

Piyush.kapoor
Piyush.kapoor

Reputation: 6803

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

Modify the replace call , use regex without quotes

Upvotes: 0

Related Questions