Ramya
Ramya

Reputation: 3

Replace params in javascript

I tried a lot to replace the query parameter using Javascript. But its not working. Can you please share any solutions to replace the parameter.

Below is the example:

console.log("www.test.com?x=a".replace(new RegExp(`${"x=a"}&?`),''));

The output I get is www.test.com ?. Is there any way to replace ? and to get only www.test.com?

Upvotes: 0

Views: 366

Answers (3)

CFLS
CFLS

Reputation: 345

You can remove all query strings using the following regex:

\?(.*)

const url = "www.test.com?x=1&b=2"
console.log(url.replace(/\?(.*)/, ''));

Upvotes: 1

Benjamín Escobar
Benjamín Escobar

Reputation: 242

If you want to remove whatever comes from the question mark including it, try this instead:

console.log("www.test.com?x=a".split("?")[0]);

That way you get only what's before the question mark.

I hope that helps you out.

Upvotes: 1

Alessio Cantarella
Alessio Cantarella

Reputation: 5201

You could brutally replace the '?x=a' string with the JavaScript replace function or, even better, you could split the string in two (based on the index of ?) with the JavaScript split function and take the first part, e.g.:

let str = 'www.test.com?x=a';
console.log(str.replace('?x=a', ''));
console.log(str.split('?')[0]);

Upvotes: 0

Related Questions