Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript replace question mark

how to make a regex for ? and = in javascript?

I want 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 prastic, not a htaccss rewrite. Thanks.

like image 612
fish man Avatar asked Jan 03 '12 20:01

fish man


2 Answers

Almost there! = is not a special character and does not need to be escaped. In addition, regex strings are not wrapped by quotes. So:

"http://localhost/search?search=words".replace(/\?search=/g, "/search/");
like image 184
Ansel Santosa Avatar answered Oct 16 '22 03:10

Ansel Santosa


How about

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

Do note that it's probably better to make a function to understand the url structure and rebuild it properly, that will produce a much more healthy, robust code, rather then a simple replacement.

like image 34
Madara's Ghost Avatar answered Oct 16 '22 02:10

Madara's Ghost