Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clean way percentage from string

How can I clean away 29% from the string below using Javascript?

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

I need some kind of way to remove all percentage so the code must work with this string too:

This is a long string which is 22% of the others.
like image 464
Jonathan Clark Avatar asked Dec 07 '11 13:12

Jonathan Clark


2 Answers

The regular expression \d+% matches one or more digits followed by a %. That is then followed by an optional space so you don't end up with two spaces in a row.

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.

Without the optional space at the end of the expression, you end up with

    // This is a long string which is  of the others.
    //-------------------------------^^
like image 164
Michael Berkowski Avatar answered Oct 19 '22 18:10

Michael Berkowski


This ought to do the job!

var s = 'This is a long string which is 29% of the others.';
s = s.replace(/[0-9]+%\s?/g, '');
alert(s);

I used so called Regular Expressions to do this. If you want more information about the solution, I'd recommend this website!

like image 25
Leonard Avatar answered Oct 19 '22 20:10

Leonard