Reputation: 425
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!'
Upvotes: 3
Views: 1239
Reputation: 11
f=
[]
.
at
[
"\
b\
i\
n\
d"
](
[
"\
H\
e\
l\
l\
o\
,\
\
W\
o\
r\
l\
d\
!"
],
0)
// Test call to the function
console.log(f())
Upvotes: 1
Reputation: 2255
Like its 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.
Upvotes: 1
Reputation:
This method uses 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);
Don't forget the output:
<p id="demo"></p>
How it Works:
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.
Upvotes: 0
Reputation: 112
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('');
}
Upvotes: -1
Reputation: 36351
Your function could just use replace
to replace the newlines:
f=_=>`H
el
lo
,w
or
ld
!`
console.log(f().replace(/\n/g, ''))
Upvotes: 0