替换标签内的第一个字符

Replace first character inside the label

本文关键字:第一个 字符 标签 替换      更新时间:2023-09-26

如何使用jQuery将每个标签的第一个字符(最后一个标签字符$ 符号除外)更改为£?

这是代码:

<p align="center" id="myradio">
    <label>$25.00 </label>
    <input checked="checked" class="hide_input" name="amount" type="radio" value="25.00" />
    <label>$50.00</label>
    <input class="hide_input" name="amount" type="radio" value="50.00" />
    <label>$100.00</label>
    <input class="hide_input" name="amount" type="radio" value="100.00" />
    <label>$250.00</label>
    <input class="hide_input" name="amount" type="radio" value="250.00" />
    <label>$500.00</label>
    <input class="hide_input" name="amount" type="radio" value="500.00" />
    <label>$1000.00</label>
    <input class="hide_input" name="amount" type="radio" value="1000.00" />
    <label>other amount</label>
    <input class="show_input" id="other" name="amount" type="radio" value="" />
</p>

您可以使用内部循环来交换字符:

$("#myradio label").html(function(){
    return this.innerHTML.replace( '$', '£' ); 
});
$("#myradio label:not(:last)").each(function() {
    $(this).text($(this).text().replace(/^'$/, "£"));
});
    $('#myradio label').each(function() {
       $(this).text('£' + $(this).text().substr(1));
    });

这基本上采用标签的子字符串,从第一个字符开始(直到结尾) - 这是没有 $ 符号的文本。并将其附加到井号。此串联文本用于替换现有文本。

$('#myradio label').html(function() {
   return this.innerHTML.replace(/^'$/,'£');
});