如何使用Javascript使字符串中的字符重复?

1sbrub3j  于 2022-12-25  发布在  Java
关注(0)|答案(6)|浏览(193)

如何使字符串中的单个字符重复给定的次数?
也就是说,如何将“XyZ”转换为“XXXyyyZZZ”?

pkwftd7m

pkwftd7m1#

试试这个:

var foo = 'bar';

function makeString(str, repeat) {
  var str = Array.prototype.map.call(str, function(character) {
    var nascentStr = '';
    while (nascentStr.length < repeat) {
      nascentStr += character;
    }
    return nascentStr;
  }).join('');
  return str;
}

alert(makeString(foo, 3));
rvpgvaaj

rvpgvaaj2#

你需要使用几个函数的组合。首先你需要将字符串拆分成单个字符:

var charArray = "XyZ".split('');

一旦你把它拆分了,你可以使用.map函数和javascript Array的一个小技巧的组合。

var someMultiplier = 5;
var duplicatedArray = charArray.map(function(char) {
  return Array(someMultiplier).join(char);
});

此时,您就有了一个包含重复字母的字符串数组,您可以使用.join将它们组合回去

var dupString = duplicatedArray.join('');
dupString === "XXXXXyyyyyZZZZZ
z8dt9xmd

z8dt9xmd3#

听起来很简单。你可以在浏览器的控制台运行这个程序:

var my = 'XyZ';

function repeat(str, times) {
  var res = '';
  for (var i in str) {
    var char = str[i];
    for (var j=0; j < times; j++) {
      res += char;
    }
  }

  return res;
}

var his = repeat(my, 3);
console.log(his);
xmakbtuz

xmakbtuz4#

你还没有提到如果输入像xyxzy会发生什么。假设它是xxxyyxxxzzzyyy

// function takes input string & num of repitation
function buildString(input, num) {
    var _currentChar = ""; // Final output string
    for (var m = 0; m < input.length; m++) {
        //call another function which will return XXX or yyy or zzz & then finally concat it
        _currentChar += _repeatString((input.charAt(m)), num);
    }
}
// It will return XXX or yyy or ZZZ 
// takes individual char as input and num of times to repeat
function _repeatString(char, num) {
    var _r = "";
    for (var o = 0; o < num; o++) {
        _r += char;
    }
    return _r
}
buildString('XyZ', 3)

jsfiddle for Example

5jvtdoz2

5jvtdoz25#

function repeatStringNumTimes(str, num) {
    let valueCopy = str
    if (num > 0) {
        for (var i = 0; i < num - 1; i++) {
            valueCopy = valueCopy.concat(str)
        }
    } else {
        valueCopy = ""
    }
    return valueCopy;
}
repeatStringNumTimes("abc", 3);
wdebmtf2

wdebmtf26#

这些天可以做得容易得多:

const repeater = (str, n) => [...str].map(c => c.repeat(n)).join('');
    alert(repeater('XyZ', 3));

相关问题