0

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?

4
  • why are you using a template parameter that's just a hardcoded string? Commented Jun 20, 2020 at 18:14
  • You want to remove whaever comes from the question mark including it? Commented Jun 20, 2020 at 18:16
  • Why do you need a regex for "?x=a". You could just split. Or just hard code in replace Commented Jun 20, 2020 at 18:16
  • 1
    Use the URL constructor. new URL(url).hostname should work Commented Jun 20, 2020 at 18:29

3 Answers 3

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.

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

Comments

1

You can remove all query strings using the following regex:

\?(.*)

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

2 Comments

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 this is why you need to create a minimal reproducible example 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.
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]);

Comments

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.