在 JavaScript 中从字符串中去除非数字字符
本文介绍了他们如何从字符串变量中删除非数字字符。本文将解释 Regex 的工作原理以及如何使用它。
Regex
代表正则表达式。Regex
是 JavaScript 中的对象,由一些特殊模式组成,可以帮助我们匹配多个字符串字符组合。
它们也可以中断或分割一些字符。在程序中编写正则表达式有两种不同的方法。
语法 1:
let re = /ab+c/;
语法 2:
let re = new RegExp('ab+c');
我们在这个代码段中使用 constructor
函数来表示表达式。表达式可以在运行时更改并在运行时编译。
replace()
函数从存储匹配模式的现有字符串创建一个新字符串。原始字符串保持不变,可以在创建新字符串后访问。
例子:
let q = 'I am dancing while you listen to music';
console.log(q.replace('dancing', 'singing'));
// expected output: "I am dancing while you listen to music"
let regex = /you/i;
console.log(q.replace(regex, 'I'));
// expected output: "I am dancing while I listen to music"
// actual output: "I am dancing while I listen to music"
console.log(q);
// expected output: "I am dancing while you listen to music"
// actual output: "I am dancing while you listen to music"
我们定义了一个字符串变量命名 q
。我们将跳舞
和你
这两个词替换为唱歌
和我
。
然后我们显示结果字符串,并且输出也显示为代码作为注释。
我们将在字符串上使用 replace()
函数,只保留整数值并删除非整数值。
例子:
let og = "-123.456abcdefgfijkl";
let updated = og.replace(/[^\d.-]/g, '');
console.log(updated);
//expected output: "-123.456"
我们使用了两个字符串变量。第一个有一些我们想要分离的非数字字符,所以我们创建了另一个变量并使用了 replace()
方法。
\d
用于匹配整数。但是,/g
告诉表达式在第一次替换后继续工作。
match()
函数将字符串与某个正则表达式匹配,并返回与正则表达式匹配的字符串。原始字符串保持不变。
但是,在程序执行期间可以随时访问和使用这个新字符串。返回的字符串将以数组形式返回。
例子:
var og = "-123.456abcdefgfijkl";
var updated = og.match(/\d/g);
console.log(updated);
join()
函数将字符串组合成一个字符串。join()
函数将两个或多个字符串一个接一个地连接起来,看起来像一个字符串。
我们在从 Match 函数生成的输出中使用了这个函数,这将为我们提供连接的单个字符串。
例子:
var og = "-123.456abcdefgfijkl";
var updated = og.match(/[\d.-]/g);
var joined = updated.join("");
console.log(joined);
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
用 jQuery 检查复选框是否被选中
发布时间:2024/03/24 浏览次数:102 分类:JavaScript
-
在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的
jQuery 中的 Window.onload 与 $(document).ready
发布时间:2024/03/24 浏览次数:180 分类:JavaScript
-
本教程演示了如何在 jQuery 中使用 Window.onload 和 $(document).ready 事件。