如何使用Javascript从下面的字符串中清除29%?从字符串中清除方式百分比
This is a long string which is 29% of the others.
我需要某种方法来消除所有比例,从而使代码必须以该字符串工作太:
This is a long string which is 22% of the others.
如何使用Javascript从下面的字符串中清除29%?从字符串中清除方式百分比
This is a long string which is 29% of the others.
我需要某种方法来消除所有比例,从而使代码必须以该字符串工作太:
This is a long string which is 22% of the others.
正则表达式匹配\d+%
一个或多个数字后跟一个%
。这随后是一个可选的空间,这样你就不会在一行中的两个空格结束。
var s = "This is a long string which is 29% of the others.";
s = s.replace(/\d+% ?/g, "");
console.log(s);
// This is a long string which is of the others.
没有在表达式的结束可选的空间,你最终
// This is a long string which is of the others.
//-------------------------------^^
这应该做的工作!
var s = 'This is a long string which is 29% of the others.';
s = s.replace(/[0-9]+%\s?/g, '');
alert(s);
我用所谓的正则表达式做到这一点。如果您想了解更多关于解决方案的信息,I'd recommend this website!
关闭!但它只能删除%符号。我也需要删除数字。所以从上面的字符串我也需要删除29。 –
@Jonathan:如果你需要支持小数(例如“Blah blah 22.5%blah blah”),我相信正则表达式是'/ \ d +(?:\。\ d +)?%/ g'。 –
@Jonathan:我认为你一定是错误地复制了Zanathiel的答案,对我很有用(我的小数正则表达式也适用于整数):http://jsbin.com/inarux注意Michael关于后面的空间的观点,但是。 –
为什么不只是做
This is a long string which is <span id="pct">29%</span> of the others.
然后当你想这一些改变javascript只是使用:
var i = 22; //change this to what you want :)
document.getElementById("pct").innerHTML = i +"%";
承认这很可能,但OP不一定*在Web浏览器上执行此操作。 JavaScript被限制在网页浏览器中的日子已经真正消失了(如果它们真的存在的话)。 –
@ T.J.Crowder:更可能的是,OP在浏览器中这样做,但仅仅是出于与DOM无关的原因。 – rvighne
你可以使用正则表达式来替换后面跟着“%”的数字
var str = "This is a long string which is 29% of the others.";
var withoutPercentage = str.replace(/(\d+%)/, "");
不需要捕获组。 –
同意你的意见。 –
你最好的选择可能是经常性的。这个表达式将让你的百分比:\d+%
。
所以这样的事情应该做的伎俩:
var s='This is a long string which is 22% of the others.';
s= s.replace(/\d+%/g, 'REPLACE');
alert(s);
你提到处理的空白。下面是处理百分比内的空白和潜力小数点的解决方案:
s = s.replace(/(?)\d+(?:\.\d+)?%(?)/g, function(m, c0, c1) {
if (c0 === " " && c1 === " ") {
return " ";
}
return "";
});
这里是如何工作的:
(?)
是捕获在数字前面的空间,如果有一个捕获组。如果没有一个,它就什么也没有,因为?
使空间可选。\d+
与前几位数字匹配。(?:\.\d+)
匹配一个可选小数点后跟更多数字。 (这是不是捕获集团,(?:xxx)
格式是没有捕捉分组;在?
后更是令整个事情可选。)%
当然匹配%
。(?)
最后捕获%
后面的空格,如果有的话;它也是可选的。String#replace
允许您提供将被调用的函数,而不仅仅是一个简单的替换字符串。如果你也想处理像.25%
的东西,正则表达式修改了一下:
/(?)(?:(?:\d+\.\d+)|(?:\.\d+)|(?:\d+))%(?)/g
击穿:
(?)
- 和以前一样。(?:...|...|...)
- 一个替代,它将匹配给出的替代方案之一。我们给出的替代方案是:
(?:\d+\.\d+)
- 一个或多个数字后跟一个小数点后面跟一个或多个数字。(?:\.\d+)
- 一家领先的小数点后面跟着一个或多个数字(?:\d+)
- 只是一系列的数字%
- 匹配%
(?)
- 和以前一样其余的都是一样的。
你在这里干什么?我甚至都没有看到你有答案! ;)+1 – RightSaidFred
反正我得到这个空间。 –