我必须删除数字和百分号之间的所有空格。字符串也可以包含所有其他符号。仅应删除数字和百分比之间的空格,而不应删除任何其他符号和百分比之间的空格。
例子:
str = "test 12 %"; // expected "test 12%"
str = "test 1.2 %"; // expected "test 1.2%"
str = "test 1,2 % 2.5 %"; // expected "test 1,2% 2.5%"
str = " % test 1,2 % 2.5 % something"; // expected " % test 1,2% 2.5% something"
我想我已经设法创建了匹配“带百分号的十进制数”的正则表达式,但是,我不知道如何“替换这个匹配数字中的空格”。
var r = /\(?\d+(?:\.\d+)? ?%\)? */g;
最佳答案
代码
(\d) +(?=%)
替换:$1
用法
const regex = /(\d) +(?=%)/g
const a = ['test 12 %','test 1.2 %','test 1,2 % 2.5 %',' % test 1,2 % 2.5 % something']
const subst = `$1`
a.forEach(function(str) {
console.log(str.replace(regex, subst))
})
解释
(\d)
捕获一个数字到捕获组 1+
匹配一个或多个空格(?=%)
积极的前瞻确保接下来是%
关于javascript - 从所有数字和百分比之间的字符串中删除空格(javascript 正则表达式),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48306231/