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
replace & to & , <lt to < and >gt to gt in javascript
提问by rafat
I want to replace &
to &
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 &
into the textbox. How could &
be removed from EmployeeCode? can anyone help...
我想替换&
为&
使用 javascript。这是我的示例代码。EmployeeCode 可以包含 &。EmployeeCode 是从 Datagrid 中选择的,它显示在“txtEmployeeCode”文本框中。但是,如果 EmployeeCode 包含任何内容,&
则它会显示&
在文本框中。如何&
从 EmployeeCode 中删除?谁能帮忙...
function closewin(EmployeeCode) {
opener.document.Form1.txtEmployeeCode.value = EmployeeCode;
this.close();
}
回答by Edgar Villegas Alvarado
With this:
有了这个:
function unEntity(str){
return str.replace(/&/g, "&").replace(/</g, "<").replace(/>/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 &
<
and >
):
可选如果您使用的是 jQuery,这将解码任何 html 实体(不仅是&
<
和>
):
function unEntity(str){
return $("<textarea></textarea>").html(str).text();
}
Cheers
干杯
回答by MultiplyByZer0
Try this:
试试这个:
var str = "&";
var newstring = str.replace(/&/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&bla"
var decoded = div.firstChild.nodeValue;
your converted value is now in decoded
您的转换价值现在在 decoded
回答by bjb568
A regex-abuse-free method:
一种无正则表达式滥用的方法:
function closewin(EmployeeCode) {
opener.document.Form1.txtEmployeeCode.value = EmployeeCode.split('&').join('&');
this.close();
}