JavaScript regex to replace a character ignoring HTML tags

前端 未结 2 1039
温柔的废话
温柔的废话 2021-01-24 08:02

Once again, I need some help and I appreciate you all for being here willing to help.
I\'m trying to implement a regex for a JavaScript function that will replace a string o

相关标签:
2条回答
  • 2021-01-24 08:18

    This will work as long as the amounts are always formatted like $36.<sup>07</sup>.

    function getAmount (s) { 
      var r = /\$([^<]+)<sup>(\d+)/.exec(s); 
      return r[1]+r[2]; 
    }
    
    getAmount("$36.<sup>07</sup>");
    // returns "36.07"
    
    0 讨论(0)
  • 2021-01-24 08:27

    You can solve this easily with jQuery:

    jQuery.trim( jQuery('label').text() )
    

    That will strip the tags for you, and produce $36.07 which you can then test with a much simpler regex.


    (If you're not currently using jQuery, and don't want to use it, you can still take a look at the source code for it and see how they've implement the .text() function in order to emulate it.)


    Hmmm, Re-reading your question, you might be asking something else - to retrieve all labels containing $ (and ignore the inputs) you can do:

    jQuery('label:contains($)')
    

    or

    jQuery('label').each( checkForDollars );
    
    function checkForDollars()
    {
        if ( jQuery(this).text().matches(/\$\d{2,5}/) } )
        {
            // do something
        }
    )
    
    0 讨论(0)
提交回复
热议问题