How to encode a String in Angularjs?

11,922

Solution 1

Javascript has special function for this purpose encodeURIComponent

encodeURIComponent escapes all characters except the following: alphabetic, decimal digits, - _ . ! ~ * ' ( )

while encodeURI also does not encode ; , / ? : @ & = + $ # characters.

Solution 2

Use encodeURIComponent for that.

check this fiddle.

var a = "wo?d";
alert(encodeURIComponent(a));

For angular specific look this SO answer.

still some problem then post me.

Share:
11,922
Pracede
Author by

Pracede

Java,J2EE, Spring, Spring, Hibernate,AngularJS, Javascript, Jquery, Bootstrap,NodeJS, MongoDB, Express

Updated on July 20, 2022

Comments

  • Pracede
    Pracede almost 2 years

    I use Angularjs to send a get http request to my server. The server respond to rest request using Spring MVC. Here a snippet code on my angular url building :

    var name="myname";
    var query= "wo?d";
    var url = "/search/"+query+"/"+name;
    

    Here Spring MVC Controller :

    @RequestMapping( value = "/search/{query}/{name}" , method = RequestMethod.GET , produces = MediaType.APPLICATION_JSON_VALUE )
    @ResponseBody
    public List<Data> search() {
    
        // search logic
    
    return data;
    }
    

    I have the problem when the query contains question mark character ( ? ). The url is split so that Spring responds : WARN o.s.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/my-server/web/search/wo in DispatcherServlet with name 'mvc'

    This is right because the question marks ? introduce the begining of request parameters. I've tried to use the js function encodeURI(query) but the question mark character is not encoded. How to encode a question mark in url ? Thanks