Reputation: 21
I want to check the first character of the string, if it is equal to 5
, then replace it by "five"
. I am using the following code, but it can only check the whole string, not the first character. Thank you.
<script type="text/javascript">
var str="div.productView-description-tabContent";
$(document).ready( function() {
$("div.productView-description-tabContent:contains('5')").html("five");
});
</script>
Upvotes: 2
Views: 945
Reputation: 4663
I hope this helps you.
Also an example provided that you can check it here http://jsfiddle.net/nak73406/yzb5x38u/14/
Simple HTML code
<div class="productView-description-tabContent">
5 Labore irure do esse ullamco est sit qui ut duis magna voluptate mollit in laboris non aliquip in.
</div>
Jquery Code
var str= jQuery('div.productView-description-tabContent').html();
var firstChar = str.charAt(0); // Get the first char
if(firstChar == '5' || firstChar == 5 ){ // check that the first char is 5 or not
// if it was 5 then replace it with 'Five'
$("div.productView-description-tabContent").text(function () {
return $(this).text().replace("5", "Five");
});
}
Out Put
Five Labore irure do esse ullamco est sit qui ut duis magna voluptate mollit in laboris non aliquip in.
Upvotes: 5
Reputation: 370789
You can use a regular expression to replace ^5
(in English: the start of the string, followed by the character 5) with 'five'
:
const productView = document.querySelector("div.productView-description-tabContent");
productView.innerHTML = productView.innerHTML.replace(/^5/, 'five');
If there are more than one such elements, then iterate over them instead:
document.querySelectorAll("div.productView-description-tabContent").forEach((productView) => {
productView.innerHTML = productView.innerHTML.replace(/^5/, 'five');
});
Upvotes: 0