JavaScript regex to replace a character ignoring HTML tags

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 of text contained in an HTML tag, but ignoring the tag altogether.
For example:
The string I need to find and replace is the dollar sign ($), and the HTML that I'm working with looks like this:

<div class="myClass">
    <input type="radio" value="$233.93" name="myInput" id="myInputId">

As you can see, I have a dollar amount in the value attribute of the input tag, and another dollar amount inside the label tag.
All this HTML is contained within a td (table cell), which in turn is part of a table, for which I'm implementing a sorting by column functionality.
My problem is that I have not been able to come up with a regex that would ignore the HTML tags altogether and match only the string inside my label tag ($36.<sup>07</sup>).
I put together this regex: /[$](?=(\d{2,5}[.<]))/
This regex works, but only half way, because it matches the first dollar sign in the value of the value attribute, granted the regex it's not set to global, because it would replace all dollar sign and I don't wan't to do that, and I cannot change the structure of the HTML either.

Any help would be greatly appreciated. Thanks



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').each( checkForDollars );

function checkForDollars()
    if ( jQuery(this).text().matches(/\$\d{2,5}/) } )
        // do something

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]; 

// returns "36.07"


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.