JavaScript返回字符串,字符数限制为2个

时间:2018-10-29 21:22:18

标签: javascript

我正在尝试编写一个返回“ Hello,World”字符串的函数,但要求每行只能有2个字符。在我的函数中,我使用的是模板文字,并且想忽略换行符\ n。谁能建议最好的解决方案?

代码::

f=_=>`H
el
lo
,w
or
ld
!`

错误::

Expected: 'Hello, world!', instead got: 'H\nel\nlo\n,w\nor\nld\n!'

4 个答案:

答案 0 :(得分:1)

此方法使用substring()

Javascript:

const output = document.getElementById('demo');

function trimString(str, lineLength) {  
  for (var i=0; i<str.length; i+=lineLength) {
    output.innerHTML += str.substring(i, i+lineLength);
    output.innerHTML += "<br />";
  }
}

trimString('Hello World', 2);

不要忘记输出:

<p id="demo"></p>


工作原理:
这可以通过调用函数trimString(str, lineLength);来工作
-用引号引起来的字符串替换str
--用每行的字符数替换lineLength

答案 1 :(得分:0)

您的函数可以仅使用replace替换换行符:

f=_=>`H
el
lo
,w
or
ld
!`

console.log(f().replace(/\n/g, ''))

答案 2 :(得分:0)

您可以尝试:

function makeTwoCharPerLine(input) {
  return input.split('').map((char, index) => {
    return (index + 1) % 2 === 0 ? 
      `${char}${String.fromCharCode(13)}${String.fromCharCode(10)}` : char;
  }).join('');
}

答案 3 :(得分:0)

就像语法父C一样,JavaScript允许您使用反斜杠字符在源代码中转义换行符:

if

在这里,由于紧接f= _=> "\ H\ e\ l\ l\ o\ ,\ W\ o\ r\ l\ d\ !\ "; document.write(f()); 之前,实际源中的每个换行符都将被忽略,从而允许字符串继续在源中的另一行,而在父级中保留一行。

相关问题