[英]Replace selected text inside p tag
I am trying to replace the selected text in the p tag.I have handled the new line case but for some reason the selected text is still not replaced.This is the html code. 我正在尝试替换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>
This is the javascript code. 这是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();
});
});
I have also created a jsfiddle of the code. 我还创建了一个jsfiddle代码。 https://jsfiddle.net/zeeshidar/w50rwasm/ Any ideas?
https://jsfiddle.net/zeeshidar/w50rwasm/有什么想法吗?
您可以简单地执行$("#1-pagedata").html('New text here');
Since your p
doesn't content HTML but just plain text, your can use both html()
or text()
as getter and setter. 由于您的
p
不包含HTML而是仅包含纯文本,因此您可以同时使用html()
或text()
作为getter和setter。
Also, thanks to jQuery Chaining you can do all your replacements in one statement. 另外,借助jQuery Chaining,您可以在一条语句中完成所有替换操作。 So, assuming your RegExp's and replacement values are correct, try:
因此,假设您的RegExp和替换值正确,请尝试:
var $p = $('#1-pagedata');
$p.text($p.text().replace(/\r?\n|\r/g,"").replace(/[^\x20-\x7E]/gmi, "").replace(val,"textbefore" + val + "textAfter"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.