Javascript replace question mark

how to make regex for ? and = in javascript?

I need something from

http://localhost/search?search=words

to

http://localhost/search/search/words

(? search =) to (/ search /)

 <script> var ss = "http://localhost/search?search=words".replace("/\?search\=/g", "/search/"); document.write(ss); </script> 

BTW: just some right, not rewriting htaccss. Thanks.

+4
source share
3 answers

Almost there! = not a special character and does not need to be escaped. In addition, regular expression strings are not wrapped in quotation marks. So:

 "http://localhost/search?search=words".replace(/\?search=/g, "/search/"); 
+16
source

You can use a simple string to replace:

 var ss = "http://localhost/search?search=words".replace("?search=", "/search/"); 
+4
source

What about

 str.replace(/[?=]/g, "/"); 

Note that it is probably best to make the function understand the URL structure and rebuild it correctly, which will create much healthier, more reliable code, and not just a replacement.

+3
source

Source: https://habr.com/ru/post/1389140/


All Articles