我正在用 img 标签替换文本编辑器中的笑脸快捷方式,但我使用的逻辑也将部分链接和标签视为笑脸快捷方式(例如 :/ http://,或者:p in cursor:pointer in the style attribute)
如何在用图像替换笑脸快捷方式时忽略所有链接和 html 标签?
for(var key in shortcuts){
// Check if the editor html contains the looped shortcut
if(content.toLowerCase().indexOf(key) != -1){
// Escaping special characters to be able to use the shortcuts in regular expression
var k = key.replace(/[<>*()?']/g, "\\$&");
// Make shortcuts case insensitive
var regex = new RegExp(k, "ig");
//Replace shortcuts with img tags (smileys)
tinymce.activeEditor.setContent(content.replace(regex,'<img src="images/transparent.png" class="smiley_icon '+ shortcuts[key] +'">'));
}
}
最佳答案
描述
我认为我处理这个问题的方法是将所有不好的和好的都匹配起来。然后在表达式中只将我感兴趣的文本字形放入捕获组。稍后在编程逻辑中我将测试每个匹配项以查看捕获组 1 是否已填充,如果是则匹配 .index
将显示字符串中发生匹配的位置。
这个表达式将找到所有 :/
, :)
, :p
、标签和网址,但捕获组 1 将仅包含 :)
, :/
, 或 :p
它们不是标签或网址的一部分。
https?:\/\/[^\s]*|<\/?\w+\b(?=\s|>)(?:='[^']*'|="[^"]*"|=[^'"][^\s>]*|[^>])*>|(:\)|:P|:\/)
展开
-
https?:\/\/[^\s]*
匹配纯文本的 url -
|
或 -
<\/?\w+\b(?=\s|>)(?:='[^']*'|="[^"]*"|=[^'"][^\s>]*|[^>])*>
匹配任何打开或关闭的 html 标签 -
|
或 -
(:\)|:P|:\/)
捕获组 1 将获得所需的文本字形
示例:
实例:http://regexr.com?35cv9 (将鼠标悬停在蓝色匹配项上以查看每个捕获组和索引)
示例文本
<a href=http://i.like.kittens style="cursor:point"> :) I had a :/ great time :p </a> check out http://some.url.com
匹配
[0] => Array
(
[0] => <a href=http://i.like.kittens style="cursor:point">
[1] => :)
[2] => :/
[3] => :p
[4] => </a>
[5] => http://some.url.com
)
[1] => Array
(
[0] =>
[1] => :)
[2] => :/
[3] => :p
[4] =>
[5] =>
)
关于javascript - 替换内容同时忽略链接和 html 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17363538/