替换p标签内的选定文本

时间:2016-05-09 18:22:44

标签: javascript jquery html replace

我正在尝试替换p标签中的所选文本。我已经处理了新的行案例,但由于某种原因,所选文本仍未被替换。这是html代码。

 <p id="1-pagedata">
(d) 3 sdsdsd random:  Subject to the classes of this random retxxt wee than   dfdf month day hello the tyuo dsds in twenty, the itol ghot qwerty ttqqo   
</p>

这是javascript代码。

 function SelectText() {
 var val = window.getSelection().toString();
 alert(val);
$('#' + "1-pagedata").html($('#' + "1-pagedata").text().replace(/\r?\n|\r/g,""));
$('#' + "1-pagedata").html($('#' + "1-pagedata").text().replace(/[^\x20-\x7E]/gmi, ""));
$('#' + "1-pagedata").html($('#' + "1-pagedata").text().replace(val,"textbefore" + val + "textAfter"));
}

$(function() {
   $('#hello').click(function() {
      SelectText();
   });
});

我还创建了一个代码的jsfiddle。 https://jsfiddle.net/zeeshidar/w50rwasm/ 有什么想法吗?

2 个答案:

答案 0 :(得分:1)

您可以执行$("#1-pagedata").html('New text here');

答案 1 :(得分:0)

由于您的p不是HTML内容而只是纯文本内容,因此您可以同时使用html()text()作为getter和setter。

另外,感谢jQuery Chaining,您可以在一个语句中完成所有替换。因此,假设您的RegExp和替换值正确,请尝试:

var $p = $('#1-pagedata');
$p.text($p.text().replace(/\r?\n|\r/g,"").replace(/[^\x20-\x7E]/gmi, "").replace(val,"textbefore" + val + "textAfter"));