Javascript 字符串函数-填充字符串

Javascript 字符串函数-填充字符串,javascript,string,function,Javascript,String,Function,leftPad函数将通过在左侧填充字符串使其具有一定的长度。我们如何使leftPad函数按如下方式工作 // If the input is empty, return an empty string leftPad('') // '' // When given just a string, it returns that string leftPad('abc') // 'abc' // When given a string and a number, it will pad the

leftPad函数将通过在左侧填充字符串使其具有一定的长度。我们如何使leftPad函数按如下方式工作

// If the input is empty, return an empty string
leftPad('') // ''

// When given just a string, it returns that string
leftPad('abc') // 'abc'

// When given a string and a number, it will pad the string with spaces
// until the string length matches that number. Notice that the code
// below does NOT add four spaces -- rather, it pads the string until
// the length is four
leftPad('abc', 4) // ' abc'

// If the padding given is less than the length of the initial string,
// it just returns the string
leftPad('abc', 2) // 'abc'

// If given a third argument that is a single character, it will pad
// the string with that character
leftPad('abc', 6, 'z') // 'zzzabc'
这是问题第一部分的当前代码-如果输入为空,则返回空字符串:

function leftPad (string, padding, character) {
    let result = ""
    if (string.length === 0) {
        return result
    }

    if (string){

    }
}

我不会回答整个问题,因为这似乎是一个家庭作业问题。但是,您可能可以充分利用内置的string函数,根据
padding
参数构建左侧的
paddedString

函数leftPad(字符串、填充、字符){
让结果为“”,padCharacter为“”;
if(string.length==0){
返回结果;
}
让paddedString=padCharacter.repeat(padding);
log('Left padding将是“'+paddedString+'”);
//归还某物
}
leftPad('hello',5);

leftPad('world',10)这是一个简单的解决方案,适用于带/不带填充字符的左填充或右填充(默认为空白)

示例:
字符串MyNewString=rightPad(MyOldString,12); 或 字符串MyNewString=leftPad(MyOldString,8,“0”)

公共静态字符串leftPad(字符串,int-length){
返回leftPad(字符串,长度为“”);
}
公共静态字符串leftPad(字符串、整型长度、字符串填充){
int L=string.length();
如果(L<长度)
返回pad.repeat(length-string.length())+string;
其他的
返回字符串;
}
公共静态字符串rightPad(字符串,整数长度){
返回rightPad(字符串,长度为“”);
}
公共静态字符串rightPad(字符串、整型长度、字符串填充){
int L=string.length();
如果(L<长度)
返回string+pad.repeat(length-string.length());
其他的
返回字符串;
}

我投票将此问题作为离题题结束,因为您不能提出与家庭作业相关的问题。那么您的问题是什么?另外,提示:@PabloSantaCruz您绝对可以提出与家庭作业相关的问题。你不能问那些尚未尝试过的广泛问题,不管这些问题是否与家庭作业有关。马克,请重新措辞,这样我们才知道真正的问题是什么。
public static String leftPad(String string, int length) {
    return leftPad(string, length, " ");
}

public static String leftPad(String string, int length, String pad) {
    int L = string.length();
    if (L < length)
        return pad.repeat(length - string.length()) + string;
    else
        return string;
}

public static String rightPad(String string, int length) {
    return rightPad(string, length, " ");
}

public static String rightPad(String string, int length, String pad) {
    int L = string.length();
    if (L < length)
        return string + pad.repeat(length - string.length());
    else
        return string;
}