0

I have a string like this:

"https://myEnv.site.org/search?q=searchTerm"

I am trying to get the searchterm.

and I succeded somewhat with this:

const returnValue = url
  .split('=')[1]
  .replace('+', ' ');

The replace is for when there is a space, like for example when value is SearchTerm withSpace

Im some scenarios I also have this charachter in the searchterm:

Something® Category® version subversion somethingElse

This turn into:

 Something%C2%+Category%C2%+version+subversion+somethingElse

I thought I could solve it by doing this:

const returnValue = url
  .split('=')[1]
  .replace('%C2%AE', '®')
  .replace('+', ' ');

Problem is that it only removes the first instance, the new value becomes:

Something® Category%C2%+version+subversion+somethingElse

I have tried a few regex attempts and Ive gotten this far which gives me the wrong result:

const returnValue = url
  .split('=')[1]
  .replace(/([~!@#$%^&*()_+=`{}\[\]\|\\:;'<>,.\/? ])+/g, '®')
  .replace(/^(-)+|(-)+$/g, ' ');

To be clear I want to replace %C2%AE with ® and the + with ' '

CodingLittle
  • 1,761
  • 2
  • 17
  • 44
  • 2
    Why reinvent the wheel? `new URL("https://myEnv.site.org/search?q=Something%AE%20Category%AE%20version%20subversion%20somethingElse").searchParams.get("q")` – epascarello Oct 19 '20 at 20:04
  • To directly address just the question asked, you need to decode the URI component. Use the global function decodeURIComponent. – Mike Fisher Oct 19 '20 at 20:09
  • returnValue=url.replaceAll('%C2%', '®').replaceAll('+', ' '); – Mahmoud Sabri Oct 19 '20 at 20:14
  • If you work on NodeJS use their URL class, in Browser Javascript it is the same code using window.URL: ```js const test = "https://myEnv.site.org/search?q=searchTerm+2" console.log(new URL(test).searchParams.get('q')) # output: searchTerm 2 ``` This will parse the URL and decode the html encoded sting in one go. – Alinex Oct 19 '20 at 20:15
  • @lbragile yes, if you have the querystring – epascarello Oct 19 '20 at 20:20
  • @ibragile new URLSearchParams(url).get('q') did not work. I got "Cannot read property 'charAt' of null" – CodingLittle Oct 19 '20 at 20:34

0 Answers0