我需要预处理queryParams并将其转换为正确的链接: 例如,用户输入以下链接:
http://myapp.com/?query=string&filter=1&sort=desc
我需要转换回所有特殊字符:
http://myapp.com/?query=string&filter=1&sort=desc
否则,queryParams对象具有以下结果:
{
amp;query: "string"
amp;filter: 1,
amp;sort: "desc",
}
答案 0 :(得分:1)
这是一个完整的例子 https://stackblitz.com/edit/hello-angular-6-decode-special
Angular 6示例
link = 'http://myapp.com/?query=string&filter=1&sort=desc';
newLink = '';
constructor() {
// I can't use a script tag in this example
this.newLink = this.decodeEntities(this.link);
}
decodeEntities(str) {
// this prevents any overhead from creating the object each time
const element = document.createElement('div');
if(str && typeof str === 'string') {
// strip script/html tags
str = str.replace(/<script[^>]*>([\S\s]*?)<\/script>/gmi, '');
str = str.replace(/<\/?\w(?:[^"'>]|"[^"]*"|'[^']*')*>/gmi, '');
element.innerHTML = str;
str = element.textContent;
element.textContent = '';
}
return str;
}
核心Javascript示例
var decodeEntities = (function() {
// this prevents any overhead from creating the object each time
var element = document.createElement('div');
function decodeHTMLEntities (str) {
if(str && typeof str === 'string') {
// strip script/html tags
str = str.replace(/<script[^>]*>([\S\s]*?)<\/script>/gmi, '');
str = str.replace(/<\/?\w(?:[^"'>]|"[^"]*"|'[^']*')*>/gmi, '');
element.innerHTML = str;
str = element.textContent;
element.textContent = '';
}
return str;
}
return decodeHTMLEntities;
})();
// I can't use a script tag in this example
var text = decodeEntities('http://myapp.com/?query=string&filter=1&sort=desc');
document.write(text);