[英]JavaScript return string with 2 char limit
我正在尝试编写一个返回“Hello, World”字符串的函数,但要求每行应该只有 2 个字符。 在我的函数中,我使用模板文字并希望忽略换行符 \\n。 任何人都可以建议最好的解决方案吗?
代码::
f=_=>`H
el
lo
,w
or
ld
!`
错误 ::
Expected: 'Hello, world!', instead got: 'H\nel\nlo\n,w\nor\nld\n!'
此方法使用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);
-
-
您的函数可以使用replace
来替换换行符:
f=_=>`H el lo ,w or ld !` console.log(f().replace(/\\n/g, ''))
你也许可以尝试:
function makeTwoCharPerLine(input) {
return input.split('').map((char, index) => {
return (index + 1) % 2 === 0 ?
`${char}${String.fromCharCode(13)}${String.fromCharCode(10)}` : char;
}).join('');
}
就像它的语法父 C 一样,JavaScript 允许您使用反斜杠字符转义源代码中的换行符:
f=
_=>
"\
H\
e\
l\
l\
o\
,\
W\
o\
r\
l\
d\
!\
";
document.write(f());
在这里,实际源中的每个换行符都被忽略,这要归功于它之前的\\
,允许字符串继续到源中的另一行,同时在父级中保留一行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.