检查字符串的第一个字符并用jquery替换它

cho*_*nny 2 jquery

我想检查字符串的第一个字符(如果是)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>
Run Code Online (Sandbox Code Playgroud)

Nas*_*imi 5

我希望这可以帮助你。

此外,还提供了一个示例,您可以在此处进行检查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>
Run Code Online (Sandbox Code Playgroud)

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"); 
      });
     }
Run Code Online (Sandbox Code Playgroud)

放出

五名劳动者在非劳动性劳动中被滥用。