javascript 如何在第 4 个和第 10 个字符后添加空格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23365092/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 00:45:53  来源:igfitidea点击:

How to add a space after 4th and 10th character

javascriptregex

提问by Zameer Khan

I have a string consisting of 15 digits Eg. 347405405655278. I need to add a blank space after 4th digit and then after 10th digit making it look like 3474 054056 55278. Can I achieve this using regular expression?

我有一个由 15 位数字组成的字符串。347405405655278. 我需要在第 4 位数字后添加一个空格,然后在第 10 位数字后添加一个空格,使其看起来像3474 054056 55278. 我可以使用正则表达式来实现吗?

As regular expressions are not my cup of tea hence need help from regex gurus out here. Any help is appreciated.

由于正则表达式不是我的菜,因此需要这里的正则表达式专家的帮助。任何帮助表示赞赏。

Thanks in advance

提前致谢

回答by Vikash Dwivedi

With the help of regular expression, you can use the given below code to achieve desired result:

在正则表达式的帮助下,您可以使用下面给出的代码来实现所需的结果:

var result = "347405405655278".replace(/^(.{4})(.{6})(.*)$/, "  ");

回答by thefourtheye

Why don't you just do substring concatenation?

为什么不直接进行子字符串连接?

var data = "347405405655278";
data = data.substr(0, 4) + " " + data.substr(4, 6) + " " + data.substr(10);
console.log(data);
# 3474 054056 55278

Or if you want to use RegEx badly, then as suggested by T.J. Crowder,

或者,如果您想严重使用 RegEx,则按照 TJ Crowder 的建议

var result = "347405405655278".replace(/^(.{4})(.{6})(.*)$/, "  ");
console.log(result);
# 3474 054056 55278

回答by sshashank124

You can do search this:

你可以搜索这个:

(.{4})(.{6})(.*)

(.{4})(.{6})(.*)

and replace with:

并替换为:

$1 $2 $3

$1 $2 $3

This will match the first 4 characters, the next 6 characters and then the rest. The replace then replaces it with the 4 characters + space + 6 characters + space + the rest.

这将匹配前 4 个字符,接下来的 6 个字符,然后是其余字符。然后替换将其替换为 4 个字符 + 空格 + 6 个字符 + 空格 + 其余部分。