2016-05-09 8 views
0

pタグで選択したテキストを置き換えようとしています。新しい行の大文字小文字を処理しましたが、何らかの理由で選択されたテキストが置き換えられません。選択したテキストをpタグ内に置き換えます

<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/ アイデアをお探しですか?

+0

http://jsfiddle.net/BGKSN/24/ – Denis

答えて

1

あなたは、単にあなたのpコンテンツHTMLが、単なるテキストがないので、あなたはゲッターとセッターとしてhtml()またはtext()両方を使用することができます$("#1-pagedata").html('New text here');

+0

実際に私は、ユーザーがその交換を選択することであると、テキストの一部を交換したいです必須 – soldiershin

0

を行うことができます。

また、jQuery Chainingのおかげで、すべての置換えを1つのステートメントで行うことができます。だから、あなたの正規表現のと置換値が正しいと仮定して、試してみてください。

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