Search code examples
javascriptregexreplacereplaceall

How to replace all "?" using javascript


I want to replace all "?" to "%3F" but it doesn't work. The Firebug console says: "SyntaxError: invalid regular expression flag %"

My code:

var q;
var replacer = new RegExp("?", "%3F");
q = (document.getElementById("q").value).replace(replacer, "");

Solution

  • The second parameter to the RegExp constructor is a string containing the flags you'd like to apply to the expression. Use the global (g) flag to replace all instances. Also, ? is a special character in regular expressions so you'd have to escape it with \.

    Try this:

    var replacer = new RegExp("\\?", "g");
    q = (document.getElementById("q").value).replace(replacer, "%3F");
    

    Or use a regex literal like this:

    var replacer = /\?/g;
    q = (document.getElementById("q").value).replace(replacer, "%3F");
    

    You should also consider using the encodeURIComponent (or possibly encodeURI) method if you want to escape all special URI characters:

    q = encodeURIComponent(document.getElementById("q").value);