I have a string in JavaScript like #box2
and I just want the 2
from it.
I tried:
var thestring = $(this).attr(\'href\');
var
For a string such as #box2
, this should work:
var thenum = thestring.replace(/^.*?(\d+).*/,'$1');
jsFiddle:
please check below javaScripts, there you can get only number
var txt = "abc1234char5678#!9";
var str = txt.match(/\d+/g, "")+'';
var s = str.split(',').join('');
alert(Number(s));
output : 1234567789
changeStrangeDate(dateString: string) {
var sum = 0;
var numbers = dateString.match(/\d+/g);
if (numbers.length > 1) {
numbers.forEach(element => {
sum += parseInt(element);
}
);
}
console.log(new Date(sum).toDateString());
return new Date(sum).toUTCString();
}
You can do it like that and then call function where you need, with parameter.
this.changeStrangeDate('/Date(1551401820000-0100)/');
This answer will cover most of the scenario. I can across this situation when user try to copy paste the phone number
$('#help_number').keyup(function(){
$(this).val().match(/\d+/g).join("")
});
Explanation:
str= "34%^gd 5-67 6-6ds"
str.match(/\d+/g)
It will give a array of string as output >> ["34", "56766"]
str.match(/\d+/g).join("")
join will convert and concatenate that array data into single string
output >> "3456766"
In my example I need the output as 209-356-6788 so I used replace
$('#help_number').keyup(function(){
$(this).val($(this).val().match(/\d+/g).join("").replace(/(\d{3})\-?(\d{3})\-?(\d{4})/,'$1-$2-$3'))
});