Replacing a number in a string with jquery

前端 未结 1 924
慢半拍i
慢半拍i 2021-02-15 04:43

I have a string which has a number in it that I would like to replace with another number.

ie

blah blah 32 blah blah<         


        
1条回答
  •  甜味超标
    2021-02-15 05:17

    Many jQuery methods like .text() can accept a function that returns the value to insert.

    Try it out: http://jsfiddle.net/6mBeQ/

    $('#my_link').text( function(i,txt) {return txt.replace(/\d+/,'other value'); });
    

    This removes the need to run the selector twice.

    Also, when you are getting an element by its ID, it is actually a little quicker if you do not include the tag name.

    So instead of

    $('a#my_link')
    

    it is better to do

    $('#my_link')
    

    as I did above.

    0 讨论(0)
提交回复
热议问题