简体   繁体   中英

str.replace within a jquery function

I have a simple jquery function as

function sendValue(str){
    $.post("test.php",{ sendValue: str },
    function(data){
        $('#display').html(data.returnValue);
    }, "json");
}

I want to replace space within the string. I thought I can do this by adding

str.replace(" ", "+");

to the second line of the function. But it did not work. I know very basic of javascript. How to replace " " with "+" in the string before posting data to test.php?

Try str.replace(/\\s/g , "+") instead. ( /\\s/ is the regex escape for whitespace).

Also are you trying to encode the string as a URL? You could use encodeURIComponent(str) which is a built in javascript method.

I think it should be the opposite

str.replace("+", " ");

I would try using

.replace(/ /g," ");

though.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM