[英]replace all \n with <br/>, all which are not inside <textarea> </textarea> tags
[英]Strip tags from text in Javascript and replace BR with linebreaks inside textarea
我需要在輸入textarea值中導入一些格式化的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>
$("#my_textarea").change(function(){
var cleanText = $("<span />").html(this.value);
this.value = cleanText.text();
});
示例: http : //jsfiddle.net/6WbXN/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.