The CreatorCon Call for Content is officially open! Get started here.

Need to split a string

ljschwaberow
Giga Expert

I feel like this should be easy enough but I'm having a hard time find information on it. I have a string value that is a department number(s) that is being passed from an AD import every morning. These department numbers will always be at least 3 digits long. For some users more than one department comes through and these numbers come through as one long string (310245610). I need to create a script that will separate them with commas every three digits. The problem I'm having is I will never know how long the string will be. How do I split this string every three digits and add a comma to separate?

1 ACCEPTED SOLUTION

tltoulson
Kilo Sage

Hi Lindsey,



The most succinct way is to use a Regular Expression like so:



var str = '123456789';   // Swap this out for your imported number


str = str.match(/.{1,3}/g); // Match any character (.) up to 3 times ({1,3}).   Creates an array of equal length strings


str = str.join(','); // Joins strings back together separated by a comma


View solution in original post

2 REPLIES 2

tltoulson
Kilo Sage

Hi Lindsey,



The most succinct way is to use a Regular Expression like so:



var str = '123456789';   // Swap this out for your imported number


str = str.match(/.{1,3}/g); // Match any character (.) up to 3 times ({1,3}).   Creates an array of equal length strings


str = str.join(','); // Joins strings back together separated by a comma


Abhinay Erra
Giga Sage

Lindsey,



  Assume you are storing the department numbers in a variable


var dept='12234444444...';


var result = dept.replace(/(\d)(?=(\d{3})+$)/g, '$1,'); //this will give you comma separated groups of 3 digits




Thanks,


Abhinay



PS: Hit like, Helpful or Correct depending on the impact of the response