[英]Wrap a sub-string with paragraph tag in a string in content editable div
Heres the html -: 继承人的HTML-:
<div contenteditable="true">I am a good person</div>
Now how to i wrap the sub-string which starts at index 7 to index 17
with a paragraph tag, so that the result is like this -: <div contenteditable="true">I am a <p>good person</p> </div>
现在如何使用段落标记将以
index 7 to index 17
开头的子字符串包装index 7 to index 17
,以便结果如下:- <div contenteditable="true">I am a <p>good person</p> </div>
Somethinng like: 像这样的东西:
function wrapSubstring(sourceString, subString, tag) {
return sourceString.replace(new RegExp("(" + subString + ")", "g"), "<" + tag" + ">$1</" + tag + ">");
}
The above will replace all instances of subString in sourceString. 上面的代码将替换sourceString中所有subString实例。
Important If subString can contain arbitrary text you'll need to quote subString. 重要说明:如果subString可以包含任意文本,则需要引用subString。 See: How to escape regular expression in javascript?
请参阅: 如何在javascript中转义正则表达式?
And a less generic implementation: 还有一个不太通用的实现:
// Wrap a subString of sourceString with the given tag
// starting at startIndex(inclusive) and going to endIndex(exclusive)
function wrapSubstring(sourceString, tag, startIndex, endIndex) {
return sourceString.substring(0, startIndex)
+ "<" + tag + ">"
+ sourceString.substring(startIndex, endIndex)
+ "</" + tag + ">"
+ (endIndex ? sourceString.substring(endIndex) : "");
}
Here's a sample call using jquery: 这是一个使用jquery的示例调用:
var $element = $('#someId');
$element.html(wrapSubstring($element.html(), 'p', 7, 17);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.