简体   繁体   中英

Wrap text in span after string - using jquery/javascript

I want to wrap text in span after the word "Price" using JavaScript/JQuery not php. I tried following but it is not working. I used an expression which I know from PHP.

 $('h2#Price').text().replace(/(.*?)Price(.*?)/, '$1 Price <span>$2</span>'); 
 span { background-color:yellow } 
 <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> 

I want to wrap "in Canada" in span.

You need to use .html to add spans

 $('#Price').html(function() { return this.innerText.replace(/(.*)Price(.*)/,'$1 Price <span>$2</span>') }); 
 span { background-color:yellow } 
 <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> 

More generic - add a class and each of them will be changed in one go:

 $(function() { $('.price').html(function() { return this.innerText.replace(/(.*)Price(.*)/, '$1 Price <span>$2</span>') }); }); 
 #PriceCAD span { background-color: yellow } #PriceMXN span { background-color: orange } 
 <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 175 

Hi Please check below code for reference

 $(document).ready(function() { var string_to_slipt = $('#Price').html(); //console.log(string_to_slipt); var ret = string_to_slipt.split("Price"); var str1 = ret[0]; var str2 = ret[1]; $('#Price').html(str1 + 'Price <span>' + str2 + '</span>'); }); 
 span { color: red; } 
 <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> 

 var text = 'Price in 12312412'; text = text.replace(/(.*Price)(.+)/, '$1 <span>$2</span>'); console.log(text); 

 document.getElementById('price').innerHTML = 'T-shirt Price in <span>Canada</span>'; 
 span { background-color:yellow } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <h2 id="price">T-shirt Price in Canadaa</h2> 

Take this, probably some type error have got in your code, now I've fixed that. You told us that you know little js and that is not a problem. If you start out with basics, you will definitely learn it. I just changed the innerHTML(things inside the tags). Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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