jQuery text() with replace() doesn't replace the text

前端 未结 5 435
甜味超标
甜味超标 2021-01-19 19:45

I have the following H2:

Password reset instructions have been sent to *|RESETPASSWORDEMAIL|*

I

相关标签:
5条回答
  • 2021-01-19 20:06

    Use this instead :

    $('#resetPWSuccess').text(
       $('#resetPWSuccess').text().replace('*|RESETPASSWORDEMAIL|*', emailAddress)
    ).show();
    

    Note that I also removed the h2 from your selector : it's useless and slower than just using the id. When you ask jQuery to search for #resetPWSuccess, it uses the very fast native getElementById function.

    From jQuery's source code :

    // Shortcuts
    if ( (match = rquickExpr.exec( selector )) ) {
        // Speed-up: Sizzle("#ID")
        if ( (m = match[1]) ) {
            if ( nodeType === 9 ) {
                elem = context.getElementById( m );
    
    0 讨论(0)
  • 2021-01-19 20:06

    I'd suggest a different approach:

    <h2 id="resetPWSuccess">Password reset instructions have been sent to <span id="resetPWemail"></span></h2>
    

    And the corresponding js:

    $('#resetPWemail').text(emailAddress);
    $('#resetPWSuccess').show();
    
    0 讨论(0)
  • 2021-01-19 20:11

    Use like that.

    $('#resetPWSuccess').text(
      $('#resetPWSuccess').text().replace('*|RESETPASSWORDEMAIL|*', 'neeraj@gmail.com')
    )
    

    See Demo Demo

    0 讨论(0)
  • 2021-01-19 20:21

    You can even simply do this

     <h2 id='resetPWSuccess'></h2>
    
     $('h2#resetPWSuccess').text('Password reset instructions have been sent to '+emailaddress).show();
    
    0 讨论(0)
  • 2021-01-19 20:22

    Try this

    $("#resetPWSuccess").text(
      $('#resetPWSuccess').text().
         replace('*|RESETPASSWORDEMAIL|*', $("#EmailID").val()))
    
    0 讨论(0)
提交回复
热议问题