在JavaScript中从字符串中删除所有非数字字符 [英] Strip all non-numeric characters from string in JavaScript

查看:106
本文介绍了在JavaScript中从字符串中删除所有非数字字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑一个非DOM场景,您希望使用JavaScript / ECMAScript从字符串中删除所有非数字字符。应保留0到9范围内的任何字符。

Consider a non-DOM scenario where you'd want to remove all non-numeric characters from a string using JavaScript/ECMAScript. Any characters that are in range 0 - 9 should be kept.

var myString = 'abc123.8<blah>';

//desired output is 1238

你将如何在平原实现这一目标JavaScript的?请记住这是一个非DOM场景,所以jQuery和其他涉及浏览器和按键事件的解决方案都不合适。

How would you achieve this in plain JavaScript? Please remember this is a non-DOM scenario, so jQuery and other solutions involving browser and keypress events aren't suitable.

推荐答案

使用字符串的 .replace 方法,正则表达式为 \D ,这是一个匹配所有非数字的速记字符类:

Use the string's .replace method with a regex of \D, which is a shorthand character class that matches all non-digits:

myString = myString.replace(/\D/g,'');

这篇关于在JavaScript中从字符串中删除所有非数字字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆