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

Jongware
  • 22,200
  • 8
  • 54
  • 100
moustacheman
  • 1,424
  • 4
  • 21
  • 47

4 Answers4

3

Much more simpler one without using | operator.

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

DEMO

Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
1

You can use the following regex:

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

See Fiddle

karthik manchala
  • 13,492
  • 1
  • 31
  • 55
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);
blairmeister
  • 915
  • 1
  • 6
  • 16
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,'');
Community
  • 1
  • 1