我需要在输入文本区域值中导入一些格式化的 html 文本
我使用jquery
那么最好的方法是什么?
我想首先我需要替换
然后删除其余部分(粗体,斜体,图像等..)
最佳答案
在我的第一个回复中,我没有看到您想要保留换行符,所以这里有一个更好的版本。它将 br 替换为不太可能的字符串 %%br%%,然后最后用换行符 (\n) 替换它们。因此,如果该字符串实际出现在文本中,它将被新行替换。您可以将其更改为您喜欢的任何内容,只需将其设置为文本中不太可能遇到的内容即可。
<script>
function removeMarkup(m) {
var d = document.createElement('div');
d.innerHTML = m;
var c = 0;
// Make brString something that should never appear in the text
// and has no special meaning in a RegExp
var brString = '%%br%%'
var re = new RegExp('\\s*' + brString + '\\s*','g');
function getTextWithReturns(node) {
var tag = node.tagName && node.tagName.toLowerCase();
var nodes = node.childNodes;
var type = node.nodeType;
var s = '';
// Deal with br
if (tag == 'br') {
return brString;
}
if (nodes && nodes.length) {
for (var i=0, iLen=nodes.length; i<iLen; i++) {
s += getTextWithReturns(nodes[i]);
}
} else if (type == 3 || type == 4) {
s += node.nodeValue
}
return s;
}
return reduceWhitespace(getTextWithReturns(d)).replace(re,'\n');
}
function reduceWhitespace(s) {
return s.replace(/^\s*/,'').replace(/\s*$/,'').replace(/\s+/g,' ');
}
</script>
<div id="d0">some text <i>more</i> text
<p>Here is a paragraph with some <b>bold</b> and <i>italic</i> text, plus a <span>span</span> and a line break break break<br> about there.</p>
<p>Here is another paragraph with some <b>bold</b> and <i>italic</i> text, plus plus a <span>span</span> and a line break <br> here.</p>
</div>
<form>
<textarea id="ta0" rows="10" cols="50"></textarea>
<button type="button" onclick="
var ta = document.getElementById('ta0');
var div = document.getElementById('d0');
ta.value = removeMarkup(div.innerHTML);
">Set value</button><input type="reset">
</form>
关于javascript - 从 Javascript 中的文本中去除标签,并用文本区域内的换行符替换 BR,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5481761/