Regex using javascript to return just numbers

2019-01-01 13:30发布

If I have a string like "something12" or "something102", how would I use a regex in javascript to return just the number parts?

8条回答
爱死公子算了
2楼-- · 2019-01-01 14:05

I guess you want to get number(s) from the string. In which case, you can use the following:

// Returns an array of numbers located in the string
function get_numbers(input) {
    return input.match(/[0-9]+/g);
}

var first_test = get_numbers('something102');
var second_test = get_numbers('something102or12');
var third_test = get_numbers('no numbers here!');

alert(first_test); // [102]
alert(second_test); // [102,12]
alert(third_test); // null
查看更多
还给你的自由
3楼-- · 2019-01-01 14:10

If you want only digits:

var value = '675-805-714';
var numberPattern = /\d+/g;
value = value.match( numberPattern ).join([]);
alert(value);
//Show: 675805714

Now you get the digits joined

查看更多
登录 后发表回答