0

I have string where I want to remove any letters and hyphens. I have a code like below,

var s = '-9d 4h 3m',
    t = '1-22';

var p = /[^0-9-]+/g;
    r = s.replace(p, ''),
    a = t.replace(p, '');

console.log(r, a);

Here I want to remove hyphen if it is in between the numbers and omit at first. Any help or suggestions?

Fiddle

6
  • So basically you're expecting -943, 122 ? Commented May 21, 2015 at 10:17
  • @adeneo, exactly! you are right. Commented May 21, 2015 at 10:17
  • And you want to remove trailing hypens as well, or just "between" the numbers ? Commented May 21, 2015 at 10:18
  • @adeneo, trailing hypens and not just the one in between. Commented May 21, 2015 at 10:19
  • @aravindtrue your question is totally unclear for me. Commented May 21, 2015 at 10:20

4 Answers 4

3

Much more simpler one without using | operator.

string.replace(/(?!^-)\D/g, "")

DEMO

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

1 Comment

I just thought of replacing with \D.. +1 :P
1

You can use the following regex:

var p = /[^0-9-]+|(?:(?!^)-)/g;

See Fiddle

3 Comments

OMG, i just failed to combine both of the regexs.
@AvinashRaj happens.. :)
I think that /[^0-9-]+|((?!^)-)/g would be enough, i.e. non-captive ?: is redundant
0

In your console log you put a comma between the variable but you need a plus like this. I have also change variable a so that it removes the -

var s = '-9d 4h 3m';
var t = '1-22';

var p = /[^0-9-]+/g;
var r = s.replace(p, '');
var a = t.replace("-", '');

console.log(r + " " + a);

Comments

0

https://stackoverflow.com/a/1862219/3464552 check over here this will be a solution.

var s = '-9d 4h 3m',
s = s.replace(/\D/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.