0

I tried a lot to replace the query parammeter 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 am getting is www.test.com? . Is there any way to replace ? and to get only www.test.com.

Ramya
  • 3
  • 2

3 Answers3

1

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.

1

You can remove all query strings using the following regex:

\?(.*)

const url = "www.test.com?x=1&b=2"
console.log(url.replace(/\?(.*)/, ''));
CFLS
  • 345
  • 1
  • 9
  • Sorry I new to JS, I want to remove only first parameter and not all. i dont want to remove all query strings. I want to remove only "x=1" and the output should be like www.test.com?b=2 – Ramya Jun 20 '20 at 18:30
  • @Ramya this is why you need to create a [mcve] with inputs that cover all scenarios, the expected behavior and a clear problem statement. From the question, it isn't clear whether you want to get the hostname, remove the query string or only a part of the query string. – adiga Jun 22 '20 at 08:49
0

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]);
Alessio Cantarella
  • 5,077
  • 3
  • 27
  • 34