javascript 在javascript中将 & 替换为 & , <lt 到 < 和 >gt 到 gt

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20964811/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 19:43:05  来源:igfitidea点击:

replace &amp to & , <lt to < and >gt to gt in javascript

javascript

提问by rafat

I want to replace &ampto &using javascript. Here is the sample code of mine.EmployeeCode could contain &. The EmployeeCode is selected from Datagrid and its showed in "txtEmployeeCode" textbox. But if the EmployeeCode contains any &then it shows &ampinto the textbox. How could &ampbe removed from EmployeeCode? can anyone help...

我想替换&amp&使用 javascript。这是我的示例代码。EmployeeCode 可以包含 &。EmployeeCode 是从 Datagrid 中选择的,它显示在“txtEmployeeCode”文本框中。但是,如果 EmployeeCode 包含任何内容,&则它会显示&amp在文本框中。如何&amp从 EmployeeCode 中删除?谁能帮忙...

function closewin(EmployeeCode) {
     opener.document.Form1.txtEmployeeCode.value = EmployeeCode;
     this.close();
}

回答by Edgar Villegas Alvarado

With this:

有了这个:

function unEntity(str){
   return str.replace(/&amp;/g, "&").replace(/&lt;/g, "<").replace(/&gt;/g, ">");
}

function closewin(EmployeeCode) {
     opener.document.Form1.txtEmployeeCode.value = unEntity(EmployeeCode);
     this.close();
}

OPTIONALIf you are using jQuery, this will decode any html entity (not only &amp;&lt;and &gt;):

可选如果您使用的是 jQuery,这将解码任何 html 实体(不仅是&amp;&lt;&gt;):

function unEntity(str){
   return $("<textarea></textarea>").html(str).text();
}

Cheers

干杯

回答by MultiplyByZer0

Try this:

试试这个:

var str = "&amp;";
var newstring = str.replace(/&amp;/g, "&");

For more information, see MDN's documentation.

有关更多信息,请参阅MDN 的文档

回答by Jorg

In case you don't want to replace all of those html entities, you can cheat with this:

如果你不想替换所有这些 html 实体,你可以用这个作弊:

var div = document.createElement('textarea');
div.innerHTML = "bla&amp;bla"
var decoded = div.firstChild.nodeValue;

your converted value is now in decoded

您的转换价值现在在 decoded

see Decode &amp; back to & in JavaScript

解码 & 回到 & 在 JavaScript 中

回答by bjb568

A regex-abuse-free method:

一种无正则表达式滥用的方法:

 function closewin(EmployeeCode) {
      opener.document.Form1.txtEmployeeCode.value = EmployeeCode.split('&amp').join('&');
      this.close();
 }