简体   繁体   中英

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. In my function, I am using template literal and want to ignore newline \\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() :

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>



This will work by calling function trimString(str, lineLength);
- Replace str with a string surrounded in quotes.
- Replace lineLength with the number of chars per line.

Your function could just use replace to replace the newlines:

 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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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