删除字符

时间:2017-07-13 14:44:21

标签: javascript jquery

在我的页面上,我有一个文本区域。里面是一些‌个字符。

我需要删除这些。

我知道我可以使用replace来执行此操作,但是当我访问文本区域的.html()时,它们不会出现。

console.log($('#my-textarea').html());

所以做上面的替换必须有效。

如何删除这些字符?

编辑:

$('#my-textarea').html().replace(/\‌/g,'');

上述内容未能删除隐藏的字符。

2 个答案:

答案 0 :(得分:1)

replace(/‌/g, '')没有用,因为HTML和javascript使用不同的编码来表示特殊字符。

您可以使用unicode表示删除此特殊字符。



$('#replace').click(function() {
  var $text = $('#my-textarea');
  
  console.log($text.html())
  
  $text.html($text.html().replace(/\u200C/g, '?')); // ? for demo
  
  console.log($text.html())
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="my-textarea">
test test &zwnj;
test test &zwnj;
test test &zwnj;
test test &zwnj;
test test &zwnj;
</div>
<button id="replace">Replace</button>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

如果你不需要html作为某事物的价值,这可能就是这个诀窍:

console.log( $('#my-textarea').text() );

jQuery .text()方法可以很好地清理输入,只返回文本,并将其余部分剥离。