replace()
method. You have to pass a regular expression /\n/g
as the first argument, and an empty string ""
or a space " "
as the second argument to the replace()
method.
The following JavaScript code converts multiline string to single line string:
let str = `This is a Multiline String.`; str = str.replace(/\n/g, ' '); console.log(str);
Output
The g
flag in the regular expression replaces all the occurrences of \n
newline characters with a space.
You can also convert a multiline string created using the +
operator or \
operator to a single line string. The following JavaScript code shows you how to achieve this:
let str1 = 'This\n' + 'is\n' + 'a\n' + 'Multiline\n' + 'String.'; let str2 = 'This\n \ is\n \ a\n \ Multiline\n \ String.'; str1 = str1.replace(/\n/g, ' '); str2 = str2.replace(/\n/g, ''); console.log(str1); console.log(str2);
Output
This is a Multiline String. This is a Multiline String.
Note: If you are unaware of creating multiline string in JavaScript, visit this tutorial.