5

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Zameer Khan
  • 1,154
  • 1
  • 18
  • 20

3 Answers3

20

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

var result = "347405405655278".replace(/^(.{4})(.{6})(.*)$/, "$1 $2 $3");
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Vikash Dwivedi
  • 216
  • 1
  • 2
  • 3
  • Thank you for this elegant solution. I am trying to do something similar, but I need to add a space after each 3rd character counting from behind. This is for displaying a monetary amount. It should do something like this. $1000 -> $1 000; $20000 -> $20 000; $3000000 -> $3 000 000 etc. (ignore the '$' in the expression please, I just need to format the number). Is this possible? – phunder Jul 30 '19 at 15:08
  • This was featured on the Stack Overflow podcast, [episode 349](https://stackoverflow.blog/2021/06/22/podcast-349-the-no-code-apps-bringing-software-smarts-to-analog-services-disrupted-by-the-pandemic/), at 21 min 57 secs. – Peter Mortensen Jun 22 '21 at 14:26
15

Do it with 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 regular expressions badly, then as suggested by T.J. Crowder,

var result = "347405405655278".replace(/^(.{4})(.{6})(.*)$/, "$1 $2 $3");
console.log(result);
# 3474 054056 55278
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
1

You can do search this:

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

and replace with:

$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.

sshashank124
  • 31,495
  • 9
  • 67
  • 76