Javascript在字符串的第n个位置插入空格 [英] Javascript insert space at nth position in string

查看:62
本文介绍了Javascript在字符串的第n个位置插入空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下字符串:"Stackoverflow",我想在每三个数字之间插入一个空格,如下所示:"S tac kov erf low"从头开始.可以使用正则表达式吗?

Let's say I have the following string: "Stackoverflow", and I want to insert a space between every third number like this: "S tac kov erf low" starting from the end. Can this be done with regexes?

我现在通过for循环通过以下方式完成此操作:

I have done it the following way with a for-loop now:

var splitChars = (inputString: string) => {
    let ret = [];
    let counter = 0;
    for(let i = inputString.length; i >= 0;  i --) {
       if(counter < 4) ret.unshift(inputString.charAt(i));
       if(counter > 3){
        ret.unshift(" ");
        counter = 0;
        ret.unshift(inputString.charAt(i));
        counter ++;
       } 
       counter ++;
    }
    return ret;
}

我可以用某种方式缩短它吗?

Can I shorten this is some way?

推荐答案

您可以进行积极的前瞻并添加空格.

You could take a positive lookahead and add spaces.

console.log("StackOverflow".replace(/.{1,3}(?=(.{3})+$)/g, '$& '));

这篇关于Javascript在字符串的第n个位置插入空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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