'How do I URL encode spaces and the word "and"?

I need to URL encode the following characters.

Key Encoding
Space %20
and (literal word) %26

To do this, I've come up with the following code. (I need to use var because I'm targeting older browsers.)

var word = "Windows and Mac"; // This can be anything

word = word.split(" ").join("%20");
word = word.split("and").join("%26");

However, there are a few issues with this code.

  • This isn't the best solution, and there is most likely a better one available.
  • The and is case-sensitive (meaning I can't input "AND", "aNd", etc).

Is there another method to fulfill those requirements? It also needs to work on older browsers (like IE).



Solution 1:[1]

It doesn't look bad, but is better to use replace, for the and problem just use RegExp:

var word = "Windows and Mac"; // This can be anything

word = word.replace(/\s/g, "%20");
word = word.replace(/and/gmi, "%26");

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Arnav Thorat