Click here to Skip to main content
15,881,248 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more: , +
I have a div whose conenteditble property set to true.

Assume, user has typed something like

The :lazy brown fox jumps over a super :lazy dog

Now, I would like to replace second ":lazy" appears in the sentence. This is dynamic. The sentence may contain any number of ":lazy" (or "any word" which must be replaced with "some text") and only required one has to be replaced. This has to be done without losing text format already done to the sentence.

Below is the code (courtesy of Peter Leow who given this solution) which replaces only first word in the sentence.

XML
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
  $("#rewrite").click(function(){
      var regex=/\.*[:]\S*/

      var originalHtml = $('#editableDiv').html();
      var newHtml = originalHtml.replace(regex,"sleeping");
      $('#editableDiv').html(newHtml);

  });
});
</script>
</head>
<body>
<form name="myform">

<div id="editableDiv"  contenteditable="true">
        the quick <b><i>brown</i></b> fox jumps over a <b><i>:lazy </i></b>dog
</div>

<input type="button" id="rewrite" value="Rewrite">

</form>

</body>
</html>



I would like to modify this to suit needs explained above. Thanks
Posted
Updated 28-Dec-13 18:38pm
v3
Comments
What have you tried?
Basavaraj Metri 29-Dec-13 0:37am    
Hi Tadit. I edited code. Added what I tried. Thanks.
Peter Leow 29-Dec-13 7:49am    
As promised, see solution 1. Sorry for taking so long, just get off the plane.

1 solution

Check out my demo code at jsfiddle[^]
It is fully commented so as to convey the idea as clearly as possible. Hope it helps.
 
Share this answer
 
Comments
Basavaraj Metri 30-Dec-13 0:15am    
Thanks Peter. You are my Saviour. Your solution works unless sentence has inline span tag with style attributes defined in it. Here (http://jsfiddle.net/Daedalus/M4BaH/) I fixed regEx. Thanks. again
Peter Leow 30-Dec-13 0:19am    
Well done. Happy New Year to you. Cheer!
Basavaraj Metri 30-Dec-13 0:45am    
Happy New Year to you as well Peter. I have one more unsolved question. Hope you have the right answer for it. Here is the link http://www.codeproject.com/Questions/703618/How-to-get

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900