从字符串清除方式百分比

时间:2011-12-07 13:51:02

标签: javascript regex

如何使用Javascript清除以下字符串中的29%?

This is a long string which is 29% of the others.

我需要某种方法来删除所有百分比,因此代码也必须使用此字符串:

This is a long string which is 22% of the others.

7 个答案:

答案 0 :(得分:12)

正则表达式\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.
    //-------------------------------^^

答案 1 :(得分:6)

这应该做的工作!

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

答案 2 :(得分:2)

你提到过处理空格。这是一个处理百分比内空白和潜在小数点的解决方案:

s = s.replace(/( ?)\d+(?:\.\d+)?%( ?)/g, function(m, c0, c1) {
  if (c0 === " " && c1 === " ") {
    return " ";
  }
  return "";
});

现场演示:Run | Edit

以下是它的工作原理:

  • 初始( ?)是一个捕获组,如果有数字,则捕获数字前面的空格。如果没有,那么它什么都没有,因为?使空间可选。
  • \d+匹配前导数字。
  • (?:\.\d+)匹配可选小数点后跟更多数字。 (它不是不是一个捕获组,(?:xxx)格式用于分组而不捕获; ?之后是使整个事物可选。)
  • %当然与%匹配。
  • 最后( ?)会在%之后捕获一个空格(如果有的话);再次它是可选的。
  • String#replace允许您提供一个将被调用的函数,而不仅仅是一个简单的替换字符串。
  • 该函数接收完整匹配作为第一个参数,然后捕获组作为剩余参数。如果两个捕获组中都有空格,则百分比的两侧都有空格,因此我们返回一个空格(以避免在百分比之前和之后卡住单词)。否则,在百分比之前或之后都没有空间,所以我们什么也没有返回,所以我们吃了那里的空间。

如果你还想处理像.25%这样的事情,那么正则表达式会有所改变:

/( ?)(?:(?:\d+\.\d+)|(?:\.\d+)|(?:\d+))%( ?)/g

现场演示:Run | Edit

故障:

  • ( ?) - 与以前相同。
  • (?:...|...|...) - 替换,它将匹配给定的替代方案之一。我们提供的替代方案是:
    • (?:\d+\.\d+) - 一个或多个数字后跟一个小数点后跟一个或多个数字。
    • (?:\.\d+) - 前导小数点后跟一个或多个数字
    • (?:\d+) - 只是一系列数字
  • % - 匹配%
  • ( ?) - 与以前相同

其余的都是一样的。

答案 3 :(得分:1)

为什么不做呢

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 +"%";

答案 4 :(得分:1)

您可以使用正则表达式替换数字后跟“%”

var str = "This is a long string which is 29% of the others.";

var withoutPercentage = str.replace(/(\d+%)/, "");

答案 5 :(得分:1)

你最好的选择可能是正则表达式。此表达式将为您提供百分比:\d+%

所以这样的事情应该可以解决问题:

var s='This is a long string which is 22% of the others.';
s= s.replace(/\d+%/g, 'REPLACE');
alert(s);

答案 6 :(得分:0)

`var numStr =“ 100%”; var num1 = 2;

numStr = numStr.replace(“%”,“”)

var computeValue = num1 * numStr; //输出:calculateValue:200`

In Javascript Strings are immutable. Hence, we need to add methods which are available to change the characters or replace the characters in the strings.
Also, using string methods will not change the existing String but will return the newly created character string. 
For example in above code numStr is an String integer and I would like to replace the "%" character from the string with ""(empty string).
So, we can make use of String.replace("value tobe replaced", "new value");
calculateValue is an variable used to store the calculated value for num and numStr and perform the calculation.