JavaScript如何在一个字符串中每隔两个字母插入一个空格?


在本文中,我们将学习如何在字符串中每隔两个字母插入一个空格。在进入正题之前,让我们快速了解一下JavaScript中的字符串。

一个或多个字符(可以是数字或符号)的序列称为字符串。字符串在JavaScript中是不可变的原始数据类型,这意味着它们不能被修改。

让我们深入本文,学习更多关于在字符串中每隔两个字母插入空格的方法。为此,我们将使用replace()方法和正则表达式。

JavaScript中的replace()方法

replace()方法返回一个新字符串,其中一个、一些或所有匹配模式的字符都被替换为替换字符。字符串正则表达式可以用作模式,并且可以为每个匹配调用一个函数作为替换。如果模式是字符串,则只替换模式的第一个实例。

语法

以下是replace()方法的语法

string.replace(searchValue, newValue)

示例

在下面的示例中,我们运行一个脚本,在每两个字母后插入空格。

Open Compiler
<!DOCTYPE html> <html> <body> <script> function space(s) { return s.toString().replace(/\d{2}(?=.)/g, '$& '); } document.write(space(9848004322148)); </script> </body> </html>

运行上述脚本后,输出窗口将弹出并显示在网页上应用了空格(每两个字符后一个空格)的数字,因为事件触发,允许每两个字符之间有空格。

示例

考虑以下示例,我们使用正则表达式方法来应用空格。

Open Compiler
<!DOCTYPE html> <html> <body> <script> const regex = /\d{2}(?!$)/g; function Number(num) { return num.replace(regex, "$& "); } const strings = ['1234567890']; for (const string of strings) { document.write(string, '=>', Number(string)); } </script> </body> </html>

当脚本执行时,它将生成一个输出,其中包含字符串内容,并在网页浏览器上显示每两个字符后应用的空格,这是由用户执行脚本时触发的事件引起的。

示例

让我们执行以下代码,在每2个字符后应用空格。

Open Compiler
<!DOCTYPE html> <html> <body> <script> var values = "JavaScriptTutorial"; var result = values.replace(/.{1,2}(?=(.{2})+$)/g, '$& '); document.write("The actual result is="); document.write(values+ "<br>"); document.write("After inserting space at nth position=") document.write(result); </script> </body> </html>

当脚本执行时,它将生成一个输出,在网页浏览器上显示实际结果和插入空格后的结果,因为空格是在用户运行脚本时触发事件后应用的。

示例

让我们考虑另一个示例,其中我们使用slice()join()方法。

Open Compiler
<!DOCTYPE html> <html> <body> <script> var str="welcometothetutorialspoint"; function formatStr(str, n) { var a = [], start=0; while(start<str.length) { a.push(str.slice(start, start+n)); start+=n; } document.write(a.join(" ")); } formatStr(str,2); </script> </body> </html>

运行上述脚本后,输出窗口将弹出并显示在网页上应用了空格(每两个字符后一个空格)的文本,因为事件触发。

更新于:2023年1月18日

3K+ 次浏览

开启你的职业生涯

完成课程获得认证

开始学习
广告