Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to join all elements in array except first one?

I have a phone number as a string as "+22 123 234 22". I am trying to format as "+22 12323422". Below is a code I am trying. But, the length of the string array won't be constant. What would be the ideal way to do it?

var x = "+12 123 344 22";
var y = x.split(" ");
var z = y[0] + " " + y[1] + y[2] + y[3];
console.log(z);

I know I can use a for loop to achieve this as below. But I am looking for something from array methods like "Skip()" in C#.

    var x = "+12 123 344 22";
    var y = x.split(" ");
    var t = y[0]+" ";
    
    for(var a=1; a<y.length; a++){
    t+=y[a];
    }
    
    var z = y[0] + " " + y[1] + y[2] + y[3];
    console.log(t);
like image 537
amar Avatar asked Feb 02 '26 03:02

amar


1 Answers

slice might come in handy:

var x = "+12 123 344 22";
var y = x.split(" ");
var z = y[0] + " " + y.slice(1).join('');
console.log(z);

A couple of other options:

var x = "+12 123 344 22";

let [h, ...rest] = x.split(" ");
console.log(h + " " + rest.join(''))

let y = x.split(" ");
console.log(y.shift() + " " + y.join(''))

console.log(x.replace(' ', '@').replaceAll(' ', '').replace('@', ' '))
like image 86
georg Avatar answered Feb 03 '26 17:02

georg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!