我如何使用jQuery或纯JavaScript来删除标签中的BOM?
<h1 id="test">John Doe</h1>
&#13;
正如您所看到的,我在所有字母之间添加了BOM,并且它会在网站上显示正常情况,但是我试图直接修剪
的JavaScript。
我将如何执行此操作.text()
,.html()
,.innerHTML()
将返回不包含BOM的普通字符串
答案 0 :(得分:3)
您可以使用.encodeURI()和.decodeURI():
//Javascript by Id:
var div = document.getElementById('test');
var pomString = encodeURI(div.innerHTML);
pomString = pomString.replace(/%EF%BB%BF/g, '');
div.innerHTML = decodeURI(pomString);
//Javascript by Class:
var divClass = document.getElementsByClassName('test');
var pomStringClass = encodeURI(divClass[0].innerHTML);
pomStringClass = pomStringClass.replace(/%EF%BB%BF/g, '');
divClass[0].innerHTML = decodeURI(pomStringClass);
//JQuery by Id:
var divJquery = $('#jquery');
var pomJquery = encodeURI(divJquery.html());
pomJquery = pomJquery.replace(/%EF%BB%BF/g, '');
divJquery.html(decodeURI(pomJquery));
//JQuery by Class:
$('.jquery').each(function(){
var pomJFilter = encodeURI($(this).html());
pomJFilter = pomJFilter.replace(/%EF%BB%BF/g, '');
$(this).html(decodeURI(pomJFilter));
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Javascript by Id:
<h1 id="test">John Doe</h1>
<hr>
Javascript by Class:
<h1 class="test">John Doe</h1>
<h1 class="test">John Doe</h1>
<hr>
JQuery by Id:
<h1 id="jquery">John Doe</h1>
<hr>
JQuery by Class:
<h1 class="jquery">John Doe</h1>
<h1 class="jquery">John Doe</h1>
<h1 class="jquery">John Doe</h1>
&#13;