繁体   English   中英

如何用跨度包裹引用的文本?

[英]How to wrap quoted text with span?

我有一个问题,如何在引号中的文本中添加<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> 

使用String.prototype.replace()方法:

 var str = document.querySelector('div').textContent; var reg = /(".*\\")+/g var s = str.replace(reg, function(m){ return '<span style="color:blue">'+m+'</span>'; }) document.querySelector('div').innerHTML = s; 
 <div>and he said "Hello, I am Nick", some extra</div> 

如果不是正则表达式,则也可以尝试使用split-map-join

 var text = document.getElementById( "el" ).innerHTML; function transform(input) { return input.split("\\"").map( function(item,index){ if( index % 2 != 0 ){ item = '<span style="color: blue">' + item; } return item }).join(""); } document.getElementById( "el" ).innerHTML = transform(text) 
 <div id="el"> and he said "Hello, i am Nick" </div> 

'and he said "Hello, I am Nick"'.replace(/"Hello, I am Nick"/, '<span style="color: blue">$&</span>');

您可以按如下方式使用String的.replace()函数:


(1)如果要保留引号并将其放在<span>

 var source = '---- "xxxx" ---- "xxxx" ----'; var result = source.replace(/"[^"]*"/g, '<span style="color:blue">$&</span>'); console.log(result); $('#container').html(result); 
 <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script> <div id="container"></div> 

笔记:

  1. 正则表达式中的[^"]序列定义了一组字符,该字符与除双引号之外的所有字符匹配。因此, [^"]*与零个或多个非双引号的字符匹配。
  2. 替换字符串中的$&将被替换为匹配的字符。

(2)如果您不想保留报价:

 var source = '---- "xxxx" ---- "xxxx" ----'; var result = source.replace(/"([^"]*)"/g, '<span style="color:blue">$1</span>'); console.log(result); $('#container').html(result); 
 <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script> <div id="container"></div> 

  1. 正则表达式中的括号会创建一个捕获组。 (请注意,引号不在捕获组内。)
  2. 替换字符串中的$1将被第一个捕获组替换。

(3)如果要保留引号,但将其放在<span>

 var source = '---- "xxxx" ---- "xxxx" ----'; var result = source.replace(/"([^"]*)"/g, '"<span style="color:blue">$1</span>"'); console.log(result); $('#container').html(result); 
 <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script> <div id="container"></div> 

注意:这与#2相同,但是引号包含在替换字符串中,因此会将它们放回结果字符串中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM