In my recent graduation project, I need to pop up some functions to remind users of their ideas: Store a keyword message in the URL and use window.location.search to extract the text after message to pop up. Initial code:

$(function () {
	if(getUrlParam('message') != null) {
		alert(getUrlParam('message'));
	};
	// Encapsulate a function to extract the URL
	function getUrlParam(name) {
		var reg = new RegExp("(^ | &)" + name + "= (/ ^ & *) (& | $)"); // Construct a regular expression object with the target parameters
		var r = window.location.search.substr(1).match(reg);  // Match the target parameters
		if(r ! =null) return unescape(r[2]); return null; // Returns the parameter value
	};
});
Copy the code

When parsing the URL, the following occurs: Parsing is indeed parsing, but the popup is garbled

Baidu, found the reason:

“Only letters and numbers [0-9a-zA-z], some special symbols.” * ‘(),”[excluding double quotes], and reserved words that can be used unencoded in urls.”

This means that if there are Chinese characters in the URL, they must be encoded and used. The trouble is that RFC 1738 does not specify how to code, leaving it up to the application (the browser) to decide. This makes “URL coding “a confusing field.

I have tried several methods and found that the encoding function encodeURI() and decoding function decodeURI() using JavaScript are more suitable for my application: the following is the updated code:

$(function () {
	if(getUrlParam('message') != null) {
		// Decode the URL
		alert(decodeURI(getUrlParam('message')));
	};
	// Encapsulate a function to extract the URL
	function getUrlParam(name) {
		// Encode the URL
		var url = encodeURI(window.location.search);
		var reg = new RegExp("(^ | &)" + name + "= (/ ^ & *) (& | $)"); // Construct a regular expression object with the target parameters
		var r = url.substr(1).match(reg);  // Match the target parameters
		if(r ! =null) return unescape(r[2]); return null; // Returns the parameter value
	};
});
Copy the code

Usage:Chinese characters can be displayed normally this time

As a useful reference for finding a solution of article: blog.csdn.net/hanchao5272…