Home >Web Front-end >JS Tutorial >How to solve the garbled problem of javascript get

How to solve the garbled problem of javascript get

藏色散人
藏色散人Original
2021-07-01 14:35:093245browse

javascript get garbled code solution: 1. Use the decodeURIComponent() method to solve the garbled code; 2. Solve the garbled code through regular matching.

How to solve the garbled problem of javascript get

The operating environment of this article: windows7 system, javascript version 1.8.5, DELL G3 computer

How to solve the garbled problem of javascript get?

js get method to pass parameters to solve the problem of Chinese garbled characters

Option 1. JS intercepts the address bar URL parameters

The following two methods can solve the problem Garbled characters are mainly caused by using the decodeURIComponent() method,

Transcode the intercepted value again

function getQueryVariable(variable) {
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split("=");
        if (pair[0] == variable) {
            return pair[1];
        }
    }
    return (false);
}
let value=getQueryVariable(&#39;name&#39;);
console.log(value);
//此函数若想解决乱码问题需要使用decodeURIComponent()方法再次处理下
let value = getQueryVariable(&#39;name&#39;);
value = decodeURIComponent(value);
console.log(value);

Option 2. Obtain the get request parameters (solve Chinese garbled characters)

//采用正则匹配方式
function getQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return decodeURIComponent(r[2]);
    return "";
};

Recommended study: "javascript Advanced Tutorial"

The above is the detailed content of How to solve the garbled problem of javascript get. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn