JavaScript - Add delimiters to a string

Viewed 322

I'm trying to figure out a way to add some form of a delimiter to a long string in Javascript. For example, if I have a string of 26 characters (see below), is there a way for me to add a space or comma after every x (let's say in this case, every 3) number of characters in that string. Expected output: "abc def ghi jkl mno pqr stu vwx yz"

var str = "abcdefghijklmnopqrstuvwxyz";
9 Answers

I think this is the simplest way:

const str = "abcdefghijklmnopqrstuvwxyz"
const result = str.replaceAll(/(.{3})/g, '$1 ')

console.log(result)

var str = "abcdefghijklmnopqrstuvwxyz";
var ary = [];
for(i = 0, len = str.length; i < len; i += 3) {
   ary.push(str.substr(i, 3))
}
const output = ary.join(' ');
console.log(output);

EDIT: Wrapped inside a fuction

This can be done by using regex (you can replace the 3 with another number or change it to a variable using ${aNumber} to change the size of the chunks

var str = "abcdefghijklmnopqrstuvwxyz";

const delimit = (text, chunkSize, delimiter) => text.match(new RegExp(`.{1,${chunkSize}}`, 'g')).join(delimiter);

console.log(delimit(str, 3, ' ')); //output abc,def,ghi,jkl,mno,pqr,stu,vwx,yz

Use .match() with a regular expression, then join the values together using a space.

let str = "abcdefghijklmnopqrstuvwxyz";
// use regex to match
let newStr = str.match(/.{1,3}/g);
// join the arrray values back to string but add a space at each values beginning
let joined = newStr.join(" ");
console.log(joined)

An easy way to do that is to convert the string to array and back

    var str = "abcdefghijklmnopqrstuvwxyz";

    var strArr = str.split('')

    var newStr =  '', x = 0;

    for(let i = 0; i < strArr.length; i++){    

        

        if(x < 3){
            newStr += strArr[i]
            x +=1;
            
        }
        if (x == 3) {
            newStr += " "
            x = 0;
            
        }
    }

    console.log(newStr)

Can use follow method to seperate string by 3 charactors:

var str = 'abcdefghijklmnopqrstuvwxyz';
var arr=str.match(/.{1,3}/g);
var newString="";
arr.forEach(element => newString+=element+" ");
console.log(newString);
This print answer as follow:

"abc def ghi jkl mno pqr stu vwx yz "

or

var str = 'abcdefghijklmnopqrstuvwxyz';
var arr=str.match(/.{1,3}/g);
var newString=arr.join(" ");
console.log(newString);

This print answer as follow:

abc def ghi jkl mno pqr stu vwx yz

I agree with the simplest and most obvious regEx solution. But there is as well, just in case, rather for educational purposes, a functional approach:

const str = "abcdefghijklmnopqrstuvwxyz";

const s = str.split('')
             .map((x,i) => (i % 3 - 2 == 0) ? x + ',' : x)
             .join('');

console.log(s) // abc,def,ghi,jkl,mno,pqr,stu,vwx,yz

Classic solution via a recursive function:

var str = 'abcdefghijklmnopqrstuvwxyz';

function add_delimiters(s, n, d) {
  return (s.length > n)
    ? s.slice(0, n) + d + add_delimiters(s.slice(n, s.length), n, d)
    : s;
}

console.log(add_delimiters(str, 3, ',')); // abc,def,ghi,jkl,mno,pqr,stu,vwx,yz

output = "abcdefghijklmnopqrstuvwxyz".replace(/(.{3})/g, '$1 ')
console.log(output)

Related