首页 > 解决方案 > 字符串函数 - 填充字符串

问题描述

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){

    }
}

标签: javascriptstringfunction

解决方案


我不会回答整个问题,因为这似乎是一个家庭作业问题。但是您可能可以很好地利用内置的字符串repeat函数来构建paddedString基于padding参数的左侧。

function leftPad(string, padding, character) {
  let result = "", padCharacter = ' ';
  if (string.length === 0) {
    return result;
  }
  
  let paddedString = padCharacter.repeat(padding);
  console.log('Left padding will be "' + paddedString + '"');
  // return something
}

leftPad('hello', 5);
leftPad('world', 10);


推荐阅读