我想检查字符串的第一个字符,如果它是equal to 5
,然后用"five"
替换它。我使用以下代码,但它只能检查整个字符串,而不是第一个字符。谢谢。
<script type="text/javascript">
var str="div.productView-description-tabContent";
$(document).ready( function() {
$("div.productView-description-tabContent:contains('5')").html("five");
});
</script>
我希望这可以帮助你。
还有一个例子,你可以在这里查看http://jsfiddle.net/nak73406/yzb5x38u/14/
简单的HTML代码
<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代码
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");
});
}
出局
学区为五劳cupidatat的一个给电影一个非常高兴地工作,不仅软化了一些在。
您可以使用正则表达式用^5
替换'five'
(英文:字符串的开头,后跟字符5):
const productView = document.querySelector("div.productView-description-tabContent");
productView.innerHTML = productView.innerHTML.replace(/^5/, 'five');
如果有多个这样的元素,那么迭代它们:
document.querySelectorAll("div.productView-description-tabContent").forEach((productView) => {
productView.innerHTML = productView.innerHTML.replace(/^5/, 'five');
});