问题描述
我有一个div,其conenteditble属性设置为true。
假设,用户输入类似
:lazy 棕色狐狸跳过超级:懒狗
现在,我想替换句子中出现的第二个:lazy。这是动态的。句子可以包含任意数量的:lazy(或任何单词,必须用some text替换),只需要替换一个。必须完成这一操作而不会丢失已对句子进行的文本格式。
以下是代码(由Peter Leow提供此解决方案的礼貌)仅取代第一个单词句子。
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.
<!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
推荐答案
这篇关于如何替换字符串而不会丢失已对内容可编辑div中的部分文本执行的文本格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!