最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to join all elements in array except first one? - Stack Overflow

programmeradmin2浏览0评论

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
Add a ment  | 

3 Answers 3

Reset to default 6

slice 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);

发布评论

评论列表(0)

  1. 暂无评论