Search code examples
javascripturl-encoding

encoding url in javascript not encoding &


I am encoding the following string in javascript

encodeURI = "?qry=M & L";

This give me an output

qry=m%20&%20l

So the "&" from M & L is not getting encoded. What should i do?


Solution

  • Does not encode characters that have special meaning (reserved characters) for a URI. The following example shows all the parts that a URI "scheme" can possibly contain.

    Reference

    encodeURI will not encode following special charcaters

    A-Z a-z 0-9 ; , / ? : @ & = + $ - _ . ! ~ * ' ( ) #
    

    let uri = "?qry=M & L"
    
    console.log(encodeURI(uri))

    So you can use encodeURIComponent ,this will encode all the characters except these

    A-Z a-z 0-9 - _ . ! ~ * ' ( )
    

    let uri = "?qry=M & L"
    
    console.log(encodeURIComponent(uri))