javascript - 如何用span包裹引用的文本?

标签 javascript jquery regex

我有一个问题,如何添加<span style="color: blue">将文本放在引号中。

示例:

.. and he said "Hello, I am Nick"

使用正则表达式我想达到这个结果:

.. and he said <span style="color: blue>"Hello, I am Nick"</span>

我想知道如何使用正则表达式来做到这一点。目标是仅将颜色应用于引号内的文本。

最佳答案

使用.replaceWith()函数,您可以在任何带引号的文本之间添加span标签。

$(document).ready(function() {
    $("h2"). // all p tags
contents(). // select the actual contents of the tags 
filter(function(i,el){   return el.nodeType === 3; }). // only the text nodes
each(function(i, el){ 
    var $el = $(el); // take the text node as a jQuery element
    var replaced = $el.text().replace(/"(.*?)"/g,'<span class="smallcaps">"$1"</span>') // wrap
    $el.replaceWith(replaced); // and replace
    });
  
});
.smallcaps {
    color:blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<h2>and he said "Hello, i am Nick" and "I am good"</h2>

关于javascript - 如何用span包裹引用的文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38348193/

相关文章:

jquery - 无限次重复 JQuery .each() 函数

javascript - Jquery 自动完成功能无法正常工作

javascript - 无法读取未定义的属性 'user_first_name'

javascript - 使用 jQuery 平滑滚动进行导航会导致奇怪的行为

javascript - 在相关 DIV 中单击和退出时控制 jQuery 可调整大小的句柄

javascript - 如何获取包含所有重音字母、数字但不含 ".,;"和其他标点符号的主题标签

javascript - 如何替换正则表达式中的多个字符?

javascript - Js正则表达式到Python正则表达式

javascript - 如何在 angularjs 工厂中使用 json 文件返回对象数组?

javascript - 如何在 MongoDB 中更新多个对象但使用相同的数据?