我有一个类似于下面的字符串
您的统计数据:
趋势正在上升。
x * y的最新值于2018-12-09为469.44。
最大值为2896,于2018-12- 08和min在2018-12-08上为23.1。
此外,中位数为367.95,众数为23.1。
错误/错误的余地更大。
如您所见,字符串中包含float
和int
。我需要用围绕这些事件的span
标签替换所有这些事件
在这里,我设法做一些基本的事情,例如将float
和int
的实例替换为XXX
。但是问题是也有date
的出现并且使操作搞砸了。所以这就是我要做的:
var string = "Your statistics:<br>The trend is going up.<br>The most recent value for x*y on 2018-12-09 is 469.44.<br>The max was 2896 on 2018-12-08 and min was 23.1 on 2018-12-08.<br>Additionally, the median is 367.95 and the mode is 23.1.<br>There is higher margin for error/mistake."
string = string.replace(/\d+/g, "XXX");
console.log(string)
这就是我得到的:
Your statistics:<br>The trend is going up.<br>The most recent value for x*y on XXX-XXX-XXX is XXX.XXX.<br>The max was XXX on XXX-XXX-XXX and min was XXX.XXX on XXX-XXX-XXX.<br>Additionally, the median is XXX.XXX and the mode is XXX.XXX.<br>There is higher margin for error/mistake.
现在我要用float
标签将所有出现的int
和span
替换为469.44
,用<span>469.44</span>
代替,{ {1}}替换为2896
因此最终的字符串将变为:
<span>2896<span>
如何做到这一点,以确保Your statistics:<br>The trend is going up.<br>The most recent value for x*y on 2018-12-09 is <span>469.44</span>.<br>The max was <span>2896</span> on 2018-12-08 and min was <span>23.1</span> on 2018-12-08.<br>Additionally, the median is <span>367.95</span> and the mode is <span>23.1</span>.<br>There is higher margin for error/mistake.
不会混乱?
答案 0 :(得分:1)
这可以完成工作,而不会后退:
var string = "Your statistics:<br>The trend is going up.<br>The most recent value for x*y on 2018-12-09 is -469.44.<br>The max was 2896 on 2018-12-08 and min was -23.1 on 2018-12-08.<br>Additionally, the median is 367.95 and the mode is 23.1.<br>There is higher margin for error/mistake."
string = string.replace(/(\s)(-?\d+(?:\.\d+)?)([.\s])/g, "$1<span>$2</span>$3");
console.log(string)
答案 1 :(得分:1)
另一种无后顾之忧的解决方案。
var string = "Your statistics:<br>The trend is going up.<br>The most recent value for x*y on 2018-12-09 is 469.44.<br>The max was 2896 on 2018-12-08 and min was 23.1 on 2018-12-08.<br>Additionally, the median is 367.95 and the mode is 23.1.<br>There is higher margin for error/mistake."
let newStr = string.replace(/(\d+[^-]\d+|\s\d\s)(?=[^-0-9])/g,str=>`<span>${str}</span>`)
console.log(newStr)
答案 2 :(得分:0)
/(?<!-\d*)\d+(\.\d+)?(?!\d*-)/g
•(?<!something)
-否定性。我们不需要捕获后面有-\d*
的数字。
•\d
-数字,与0到9之间的任何数字匹配。
?*
-零次或多次
•\d+(\.\d+)?
-\d+
从1到多次的任何数字(整数),
•(\.\d+)
-\.
点符号,\d+
任何数字(浮点数),
•?
-“惰性”匹配,表示“零或一个匹配”
•(?!\d*-)
-否定超前。我们也不需要带有-
的数字。
let bubu = document.getElementById('bubu');
bubu.innerHTML = bubu.innerHTML
.replace(/(?<!-\d*)\d+(\.\d+)?(?!\d*-)/g, match => '<span class="red">' + match + '</span>')
.red { color: red; }
<p id="bubu">Your statistics:
The trend is going up.
The most recent value for x*y on 2018-12-09 is 469.44.
The max was 2896 on 2018-12-08 and min was 23.1 on 2018-12-08.
Additionally, the median is 367.95 and the mode is 23.1.
There is higher margin for error/mistake.</p>