简体   繁体   English

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

[英]JavaScript return string with 2 char limit

I am trying to write a function which returns "Hello, World" string but the requirement is there should be only 2 char per line.我正在尝试编写一个返回“Hello, World”字符串的函数,但要求每行应该只有 2 个字符。 In my function, I am using template literal and want to ignore newline \\n.在我的函数中,我使用模板文字并希望忽略换行符 \\n。 Can anyone suggest the best solution for it?任何人都可以建议最好的解决方案吗?

code::代码::

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

Error ::错误 ::

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

This method uses substring() :此方法使用substring()

Javascript: 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);

Don't forget the output:不要忘记输出:

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


How it Works:这个怎么运作:
This will work by calling function trimString(str, lineLength);这将通过调用函数trimString(str, lineLength);
- Replace str with a string surrounded in quotes. -用引号括起来的字符串替换str
- Replace lineLength with the number of chars per line. -用每行的字符数替换lineLength

Your function could just use replace to replace the newlines:您的函数可以使用replace来替换换行符:

 f=_=>`H el lo ,w or ld !` console.log(f().replace(/\\n/g, ''))

You could maybe try:你也许可以尝试:

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

Like it's syntactic parent, C, JavaScript allows you to escape newlines in the source with the backslash character:就像它的语法父 C 一样,JavaScript 允许您使用反斜杠字符转义源代码中的换行符:

f=
_=>
"\
H\
e\
l\
l\
o\
,\
W\
o\
r\
l\
d\
!\
";

document.write(f());

Here, every newline in the actual source is being ignored thanks to the \\ immediately before it, allowing the string to continue to another line in the source while remaining one line in the parent.在这里,实际源中的每个换行符都被忽略,这要归功于它之前的\\ ,允许字符串继续到源中的另一行,同时在父级中保留一行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM