javascript - 在js中将字符串中的每个字母加倍

标签 javascript

我需要将字符串中的每个字母加倍

abc -> aabbcc

我试试这个

var s = "abc";
for(var i = 0; i < s.length  ; i++){
   console.log(s+s);
}

对/对

>     abcabc    
>     abcabc  
>     abcabc

但我需要

aabbcc

帮助我

最佳答案

使用String#split , Array#mapArray#join方法。

var s = "abc";

console.log(
  // split the string into individual char array
  s.split('').map(function(v) {
    // iterate and update
    return v + v;
    // join the updated array
  }).join('')
)


更新:您甚至可以使用 String#replace方法。

var s = "abc";

console.log(
  // replace each charcter with repetition of it
  // inside substituting string you can use $& for getting matched char
  s.replace(/./g, '$&$&')
)

关于javascript - 在js中将字符串中的每个字母加倍,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40358037/

相关文章:

javascript - 多次调用函数并保存结果

javascript - 移动设备 - 覆盖视口(viewport)比例设置以实现缩放/平移媒体查看器?

javascript - 如何使用 Meteor 事件转动按钮并反转它们?

javascript - 电话间隙 : Custom URL handling freezing

javascript - 使用 jQuery 环绕元素组

javascript - Angular 下载大块

javascript - Canvas 绘制图像错误

javascript - jQuery Datatables 获取第一个显示的行自定义属性

javascript - 比较不同格式的日期

javascript - 如何连接(变量+对象键名)以点表示法获取对象值