sam*_*mar 2 javascript regex jquery replace
我想使用JavaScript / JQuery(而不是php)在“价格”一词后的范围内换行。我尝试了以下操作,但无法正常工作。我使用了从PHP知道的表达式。
$('h2#Price').text().replace(/(.*?)Price(.*?)/, '$1 Price <span>$2</span>');Run Code Online (Sandbox Code Playgroud)
span { background-color:yellow }Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h2 id="Price">T-shirt Price in Canada</h2>Run Code Online (Sandbox Code Playgroud)
我想将“在加拿大”包裹起来。
您需要使用.html添加跨度
$('#Price').html(function() {
return this.innerText.replace(/(.*)Price(.*)/,'$1 Price <span>$2</span>')
});Run Code Online (Sandbox Code Playgroud)
span { background-color:yellow }Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h2 id="Price">T-shirt Price in Canada</h2>Run Code Online (Sandbox Code Playgroud)
更通用-添加一个类,并且将一次更改它们:
$(function() {
$('.price').html(function() {
return this.innerText.replace(/(.*)Price(.*)/, '$1 Price <span>$2</span>')
});
});Run Code Online (Sandbox Code Playgroud)
#PriceCAD span {
background-color: yellow
}
#PriceMXN span {
background-color: orange
}Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h2 class="price" id="PriceCAD">T-shirt Price in Canada</h2>
CAD 12
<h2 class="price" id="PriceMXN">T-shirt Price in Mexico</h2>
MXN 175Run Code Online (Sandbox Code Playgroud)