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
orsubstring
. Using a regex is pointless here. – plalx Commented Oct 2, 2018 at 13:35
3 Answers
Reset to default 5You 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+$)/,'')