0

I am in need of finding and removing the "-" negative sign in front of a percentage using either Regex or jQuery.

I've tried doing this:

$('[data-excel]').each(function() { 
   $(this).html($(this).html().replace(' -', ' ')); 
});

But that doesn't seem to remove it. The reason why i have a space before the negative sign ** -** is there is a word in each that has it worded like this-and so it would pick up that one instead of the one that's the percentage on the page.

An example of what I am looking at:

About -38% is made with this-and also with something else.

Any help would be great! Thanks.

4
  • 1
    Using regedit? The Windows registry tool?? Commented Oct 21, 2014 at 15:49
  • 1
    Regedit and regular expressions (regex) are two very different things. Commented Oct 21, 2014 at 15:49
  • 1
    Oops... getting my coding lang all mixed. Corrected. Thanks @ÁlvaroG.Vicario for pointing that out :) Commented Oct 21, 2014 at 15:54
  • What about (+/-)38% ? Because nothing is made up of a negative percentage of anything. Commented Oct 21, 2014 at 16:04

3 Answers 3

1
myString.replace(/-(?=\d)/,"")

Use a lookahead to look for a - followed by a digit.

http://regex101.com/r/rV3rF3/1

For completeness, to insure that the number is actually followed by a %, simply:

myString.replace(/-(?=d+%)/,"");

To account for (optional) decimals:

myString.replace(/-(?=\d+\.?\d*%)/,"");

Which matches:

-      literal -
?=     followed by (lookahead):
d+     1 or more digits
\.?    0 or 1 decimal point
d*     0 or more digits

http://regex101.com/r/rV3rF3/2

Sign up to request clarification or add additional context in comments.

5 Comments

This doesn't ensure that the value is a percentage. This would turn "I scored -5 so now my average is -20% less than before" into "I scored 5 so now my average is 20% less than before".
@JamesDonnelly: True, but an easy fix (see vks' solution). The OP didn't state whether there are or are not other numbers in the string.
@MattBurland no other numbers are in the string. Just the percentage and text.
@StealthRT so there are no decimals? like -13.5%
@ᾠῗᵲᄐᶌ Nope, not at all.
0
-(?=\d+%)

Try this.This will look for the percentage sign after -.Replace with empty string.See demo.

http://regex101.com/r/rQ6mK9/25

1 Comment

The question is vary vague, but percentage symbols are usually placed after numbers. A negative percentage would be -5%, for instance, not -%5.
0

Try This: myStr.replace(/[/-]/g, '')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.