javascript - Inserting spaces every 3-4 characters - Stack Overflow

I have this:1231231234I wish to insert a space every 3 - 4 characters, so it's formatted like so:1

I have this:

1231231234

I wish to insert a space every 3 - 4 characters, so it's formatted like so:

123 123 1234

Is this possible with regex? I have something that enters a space every 3 characters but I am unsure how to do a mix of 3 and 4 characters to get the above format.

value.replace(/\B(?=(\d{3})+(?!\d))/g, " ");

I have this:

1231231234

I wish to insert a space every 3 - 4 characters, so it's formatted like so:

123 123 1234

Is this possible with regex? I have something that enters a space every 3 characters but I am unsure how to do a mix of 3 and 4 characters to get the above format.

value.replace(/\B(?=(\d{3})+(?!\d))/g, " ");
Share Improve this question asked Oct 2, 2018 at 13:18 panthropanthro 24.1k70 gold badges205 silver badges350 bronze badges 4
  • 2 When 3 and when 4? – sagi Commented Oct 2, 2018 at 13:19
  • It's in the example above. – panthro Commented Oct 2, 2018 at 13:29
  • So every string is made of the numbers 1, 2, 3, and 4? And it's either 123 or 1234? – Andy Commented Oct 2, 2018 at 13:32
  • Do you always have a 10 characters string without spaces? Just use slice or substring. Using a regex is pointless here. – plalx Commented Oct 2, 2018 at 13:35
Add a ment  | 

3 Answers 3

Reset to default 5

You can use a regex with lookahead.

The Positive Lookahead looks for the pattern after the equal sign, but does not include it in the match.

function format(s) {
    return s.toString().replace(/\d{3,4}?(?=...)/g, '$& ');
}

console.log(format(1234567890));
console.log(format(123456789));
console.log(format(1234567));
console.log(format(123456));
console.log(format(1234));
console.log(format(123));

value = "1231231234";

console.log(value.replace(/^(.{3})(.{3})(.*)$/, "$1 $2 $3"));

// add spaces after every 4 digits (make sure there's no trailing whitespace)
somestring.replace(/(\d{4})/g, '$1 ').replace(/(^\s+|\s+$)/,'')

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745287056a4620625.html

相关推荐

  • javascript - Inserting spaces every 3-4 characters - Stack Overflow

    I have this:1231231234I wish to insert a space every 3 - 4 characters, so it's formatted like so:1

    6小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信