-1

I need to change @x ( x a number) to x. How can I do that, I don't know js regex..

2
  • Answers where already posted and I can't comment on the question, but here is a link to regex in javascript if you want to learn more about it. Commented Apr 14, 2019 at 3:20
  • 1
    It's pretty straight forward, you can try to learn something about regex here give it a try if you still face any problem comment here will be happy to help Commented Apr 14, 2019 at 3:23

3 Answers 3

0

You can try like this.

var n = Number(s.replace(/\D+/, ''))

> var s = "@123";
undefined
> 
> var n = s.replace(/\D+/, '')
undefined
> 
> n
'123'
> 
> n = Number(n)
123
> 
> n + 7
130
> 
Sign up to request clarification or add additional context in comments.

Comments

0

Just use replace like so:

 

const str = "@1235";
const num = str.replace("@", "");
console.log(num);

Comments

0

You can use inbuilt replace function for this purpose, which can take both, literals and regex pattern as parameter.

var str = "@12345";
str.replace("@", "");

We can also use patterns in the replace parameter, if you have multiple values to be replaced.

var str = "@123#45";
str.replace(/[@#]/,"")     // prints "123#45" => removes firs occurrence only
str.replace(/[@#]/g,"")    // prints "12345"
str.replace(/\D/,"")       // prints "123#45"  => removes any non-digit, first occurrence
str.replace(/\D/g,"")      // prints "12345"  => removes any non-digit, all occurrence
  • g stands for global search
  • [@#] stands for either @ or #, you can add anything here
  • \D stands for anything other than digits

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.