10

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.

1
  • Changing from key-value pairs to single value directory doesn't make sense and can really goof up whatever encoding you've got. Yeah, you said practice, but what are you actually trying to accomplish here? Commented Jan 3, 2012 at 20:27

3 Answers 3

21

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/");
Sign up to request clarification or add additional context in comments.

1 Comment

+1 for being 120 seconds faster! =) (and, of course, absolutely correct!)
8

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.

3 Comments

Double slash does not escape a slash.
My bad, confused with a backslash. Corrected.
It will work once, but yes, it will fail on the OP's requirements. Fixed. Also, I practically wrote part of that FM, so please, me answering questions when I should be long asleep does not mean I lack in knowledge. i.qkme.me/35bp94.jpg << that's the face I made btw :)
4

You can use a simple string for replace:

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

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.