Home > Article > Web Front-end > How to solve the garbled problem of javascript get
javascript get garbled code solution: 1. Use the decodeURIComponent() method to solve the garbled code; 2. Solve the garbled code through regular matching.
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('name'); console.log(value); //此函数若想解决乱码问题需要使用decodeURIComponent()方法再次处理下 let value = getQueryVariable('name'); 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!