我有这个样本: -
代码HTML:
<p>
width (10mm)
</p>
CODE JS:
jQuery(document).ready(function(){
//First bracket detection
});
我想要获得的结构如下(在文档准备好之后):
<p>
width <span>(10mm)</span>
</p>
我以为我可以检测到字符串中的第一个括号,然后添加一个范围。
你能给我一个简单的例子,我该怎么做?
提前致谢!
答案 0 :(得分:2)
使用它:
jQuery(document).ready(function () {
var $p = $("p");
var text = $p.text().trim();
text = text.split(" ");
text = text[0] + "<span>" + text[1] + "</span>";
$p.text(text);
});
答案 1 :(得分:2)
这适用于两种情况 : -
空格/不含空格(例如width (10mm)
或width(10mm)
): -
$(document).ready(function(){
var string = $.trim($('p').text());
string = string.replace(/\(([^)]+)\)/, "<span>$1</span>");
$('p').html(string);
});
span{
font-size:30px;
color:green;
background:yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>
width (10mm)
</p>
答案 2 :(得分:0)
var $p = $('p'),
text = $p.text().trim(),
replaceWith = text.replace(/\(.+\)/, '<span>$&</span>');
$p.html(replaceWith)
span {color: red}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>width (10mm)</p>