使用正则表达式替换除第一次出现的空白子串之外的所有内容 [英] use regex to replace all but first occurrence of a substring of blanks

查看:99
本文介绍了使用正则表达式替换除第一次出现的空白子串之外的所有内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下声明可以正常运行:

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>');

但是,我现在需要动态改变最后两个变量的颜色,所以我决定将它们用class ='wt'括起来控制它们的颜色。这给出了:

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>');

失败,因为span和class之间的空格变为& nbsp ;

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

我的正则表达式能力仅与示例有关,因此问题是如何将除第一个空格之外的所有空格更改为& 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.

推荐答案

只是不要使用字符串。相反,使用jQuery / DOM操作。它不容易出错并且效率更高。

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

这篇关于使用正则表达式替换除第一次出现的空白子串之外的所有内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆