use regex to replace all but first occurrence of a substring of blanks

The following statement runs fine:

$wb.upLinearLoad.append('<div>' + sprintf("%5s%8.1f to%7.1f%8.1f%6.0f%8.0f",sLinearSegName[i][j],fLinearPtBA[i][j],fLinearPtBA[i][j+1],fLen,fLinearPtPpi[i][j],fLinearSegMaxWt[i][j]).replace(/ /," &nbsp;") + '</div>');

However, I now have a need to dynamically change the color of the last two variables only, so I decided to enclose them in a span with a class='wt' to control their color. This gives:

$wb.upLinearLoad.append('<div>' + sprintf("%5s%8.1f to%7.1f%8.1f<span class='wt'>%6.0f%8.0f</span>",sLinearSegName[i][j],fLinearPtBA[i][j],fLinearPtBA[i][j+1],fLen,fLinearPtPpi[i][j],fLinearSegMaxWt[i][j]).replace(/ /," &nbsp;") + '</div>');

which fails because the space between span and class gets changed to &nbsp;

My regex ability goes only as far the example, so the question becomes how do I change all but the first space to &nbsp;?

Any and all suggestions are most welcome, and especially if you see that my whole approach is poor.

Answers:

Answer

Just don't do it using strings. Instead, use the jQuery/DOM manipulation. It's less prone to error and more efficient.

$wb.upLinearLoad.append(
    $('<div>').append(
        sprintf("%5s%8.1f to%7.1f%8.1f", sLinearSegName[i][j], fLinearPtBA[i][j], fLinearPtBA[i][j+1], fLen),
        $('<span>').addClass('wt').text(sprintf("%6.0f%8.0f</span>", fLinearPtPpi[i][j], fLinearSegMaxWt[i][j]))[0]
    )
);

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.