简体   繁体   中英

javascript string replace special characters

I have a function that removes the filter from an html string if a checkbox is unchecked or adds it if it is checked. I am having problems removing the %20 or + symbol from in front of the string I want to remove using the string replace function.

This code works:

var addFilter = change.value;

if (change.checked == true) { //add filter }
else {
    var removeFilter1 = addFilter;
    var removeFilter2 = addFilter;

        if(currFilter != '') {
            var url = currFilter.replace(removeFilter1, "");
            var url = url.replace(removeFilter2, "");
            window.open(url, "_self");
        }

}

...basically I tried setting removeFilter1 = "%20" + addFilter; and removeFilter2 = "+" + addFilter; to get rid of the extra space characters in the url but it doesn't do anything when I make that change. I'm pretty sure it has something to do with the replace function not working with special characters but not sure how to fix. It isnt really that big of a deal because it still works with the extra spaces included but its bothering me lol.

%20 基本上是空格,它在 url 中显示为 %20 以表示空间,因为 url 不能有空格..所以你应该尝试从字符串中删除不是 %20 的空格......例如

var url = currFilter.replace(" ", "");

Have you tried decodeURI and replacing spaces?

Greets

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