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 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);
Share
Improve this question
edited Jul 8, 2021 at 5:38
amar
asked Jul 8, 2021 at 5:29
amaramar
4935 silver badges18 bronze badges
2
- @TusharShahi I added the for loop. Sorry, forgot to mention that I am looking for some array method instead of for loop. – amar Commented Jul 8, 2021 at 5:39
- 1 ok. You can use reduce too for this. – Tushar Shahi Commented Jul 8, 2021 at 6:06
3 Answers
Reset to default 6slice
might e 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('@', ' '))
Using an array method - reduce()
and having if condition for first index:
var x = "+12 123 344 22";
var y = x.split(" ");
var z = y.reduce((cum,x,index) =>{
if(index == 0) return y[0] + " ";
return cum + y[index];
},"");
console.log(z);
Use for loop
to iterate from 1 (excluding first element) to join rest of the split string.
var x = '+12 123 344 22';
var y = x.split(' ');
var z = y.length > 0 ? `${y[0]} ` : '';
for (let i = 1; i < y.length; i ++) {
z += y[i];
}
console.log(z);