1

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

2
  • 1
    @KalpeshRajai What? "str".replace(pattern/string, replacement)... Commented Jun 23, 2016 at 10:02
  • @KalpeshRajai I think u are confused, please try a jsfiddle to prove your point Commented Jun 23, 2016 at 10:13

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

3 Comments

thank you, thing is I am getting "Products" as a string from somewhere else, can I use it and add "/" to it with above ?
It works fine +1, but I am having trouble e.g. when I have this Products/Price&$expand=People, it is also removing &$expand=... part as well :(
@Mathematics Check now.
0
 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

1 Comment

In string there is also Products/Price that you do not replace.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.