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

查看:33
本文介绍了在 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天全站免登陆