I need to change @x ( x a number) to x. How can I do that, I don't know js regex..
Asked
Active
Viewed 69 times
-1
-
1It's pretty straight forward, you can try to learn something about regex [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp) give it a try if you still face any problem comment here will be happy to help – Code Maniac Apr 14 '19 at 03:23
-
Answers where already posted and I can't comment on the question, but [here is a link](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp) to regex in javascript if you want to learn more about it. – MSclavi Apr 14 '19 at 03:20
3 Answers
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
>

hygull
- 8,464
- 2
- 43
- 52
0
Just use replace
like so:
const str = "@1235";
const num = str.replace("@", "");
console.log(num);

Jack Bashford
- 43,180
- 11
- 50
- 79
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

Kamal Nayan
- 1,890
- 21
- 34