javascript - 在字符串左侧添加空格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25828924/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 21:55:59  来源:igfitidea点击:

javascript - adding white space to left of string

javascriptstring

提问by K3NN3TH

Is there a better way to add x amount of white space to a string?

有没有更好的方法向字符串添加 x 个空格?

str = "blah";
x = 4;

for (var i = 0; i < x; i++){
  str = ' ' + str;
}

return str;

回答by Declan Cook

Could do it like this, prevents the loop.

可以这样做,防止循环。

str = str + new Array(x + 1).join(' ')

str = str + new Array(x + 1).join(' ')

回答by slebetman

In ES6 you can do the following:

在 ES6 中,您可以执行以下操作:

str = ' '.repeat(x) + str;

At this point in time (late 2014) it's only available in Chrome and Firefox. But in two years it should be widely supported.

目前(2014 年末)它仅在 Chrome 和 Firefox 中可用。但在两年内应该得到广泛支持。

See the documentation for more info: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/repeat

有关更多信息,请参阅文档:https: //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/repeat

回答by Penny Liu

Alternatively using lodash _.padStart. Pads string on the left side if it's shorter than length.

或者使用 lodash _.padStart。如果字符串比长度短,则在左侧填充字符串。

const str = 'blah',
  len = str.length,
  space = 4;
console.log(_.padStart(str, len + space));
// => '    blah'
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>

Or pure JavaScript:

或纯JavaScript

const str = 'blah',
  len = str.length,
  space = 4;
console.log(str.padStart(len + space, ' '));

回答by Ezequiel García

for example you can use repeat for the white space left or right of your string:

例如,您可以对字符串左侧或右侧的空白使用重复:

var j = 6;
for (i = 0; i < n; i++) {
    console.log(" ".repeat(j-1)+"#".repeat(i+1))
    j--;
}