SDS
SDS

Reputation: 828

Parse and replace a string in JavaScript?

I've a HTML string that looks as follows

var hoverData = "<table id='hvr-revision_history'><tr><td>{date_value}2013-07-29T11:52:38Z{date_value}</td><td>Error1</td></tr><tr><td>{date_value}2013-07-30T11:52:38Z{date_value}</td><td>Error2</td></tr><tr><td>{date_value}2013-07-31T11:52:38Z{date_value}</td><td>Error3</td></tr></table>";

The final output needed is

"<table id='hvr-revision_history'><tr><td>07/29/2013 11:52:38 AM</td><td>Error1</td></tr><tr><td>07/30/2013 11:52:38 AM</td><td>Error2</td></tr><tr><td>07/31/2013 11:52:38 AM</td><td>Error3</td></tr></table>"

My approach is

var sindex = 0;
while(true){
    var sindex = hoverData.indexOf("{date_value}"); //startindex
    if(sindex <0)
        break;
    var eindex = hoverData.indexOf("{date_value}",sindex+1); //endindex
    var date = hoverData.substring(sindex+12,eindex); //string between {date_value} tags, so 2013-07-29T11:52:38Z
    //logic to parse the date
    var hoverData = hoverData.replace(date,parsedDate);                     
}
var hoverData = hoverData.replace("{date_value}","");

Is there a better approach? My code will fail if I've 2 or more dates that are exactly the same.

Upvotes: 0

Views: 1608

Answers (1)

Paul Roub
Paul Roub

Reputation: 36448

You can match the individual date chunks as a regular expression, with a function (instead of a string) as the replacement. That function can call your parse function, which I've stubbed out here since you didn't include it.

var hoverData = "<table id='hvr-revision_history'><tr>" +
  "<td>{date_value}2013-07-29T11:52:38Z{date_value}</td>" +
  "<td>Error1</td></tr>" + 
  "<tr><td>{date_value}2013-07-30T11:52:38Z{date_value}</td>" + 
  "<td>Error2</td></tr>" +
  "<tr><td>{date_value}2013-07-31T11:52:38Z{date_value}</td>" +
  "<td>Error3</td></tr></table>";

// your "logic to parse the date" would go here
function parseDate(str) {
    return "( parsed " + str + " )";    
}

// look for our delimiters with *only* the legal timestamp 
// characters between them
hoverData = hoverData.replace(/\{date_value\}([A-Z0-9\-\:]+)\{date_value\}/g,

    // match gets the fully-matched string, plus any captured patterns 
    // (the parenthesized chunk) as separate parameters. `datepart` will
    // contain the matched timestamp string only

    function (match, datepart) {
      return parseDate(datepart);
   }
);

hoverData = hoverData.replace("{date_value}","");

See it in action here: http://codepen.io/paulroub/pen/CGqlh

Upvotes: 1

Related Questions