JavaScript正则表达式-字符串开头和结尾的新行和空格


const dummyText = `First line
Second line
Third line

Last Line`
const expectedOutput = `First Line
Second line
Third line
Last Line`

dummyText.replace(/+?/g,''(,此正则表达式当前替换单词之间的所有空格。我需要删除字符串开头和结尾的空格,必须保留换行

低于输出当前我得到

FirstLineSecondlineThirdlineLastLine

我需要像预期的输出可变值

如果没有一个花哨的正则表达式,它可以是一个拆分、修剪、过滤和连接

const dummyText = `First line
Second line
Third line

Last Line`
const result = dummyText
.split(/n/)   // split on new lines
.map(x => x.trim()) //clean up the new lines
.filter(Boolean)  // remove empty lines
.join('n')  // join it back together
console.log(result);

可以使用.trim((删除中的所有空格

const greeting = '   Hello world!   ';
console.log(greeting);
// expected output: "   Hello world!   ";
console.log(greeting.trim());
// expected output: "Hello world!";

最新更新