如何使用Javascript清除以下字符串中的29%?
This is a long string which is 29% of the others.
Run Code Online (Sandbox Code Playgroud)
我需要某种方法来删除所有百分比,因此代码也必须使用此字符串:
This is a long string which is 22% of the others.
Run Code Online (Sandbox Code Playgroud)
Mic*_*ski 12
正则表达式\d+%匹配一个或多个数字后跟a %.然后是一个可选空格,这样你就不会在一行中得到两个空格.
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.
Run Code Online (Sandbox Code Playgroud)
如果没有表达式末尾的可选空格,您最终会得到
// This is a long string which is of the others.
//-------------------------------^^
Run Code Online (Sandbox Code Playgroud)
这应该做的工作!
var s = 'This is a long string which is 29% of the others.';
s = s.replace(/[0-9]+%\s?/g, '');
alert(s);
Run Code Online (Sandbox Code Playgroud)
我使用所谓的正则表达式来做到这一点.如果您想了解有关该解决方案的更多信息,我建议您访问此网站!