gpt4 book ai didi

javascript - 正则表达式 - 右/左 trim + 将中间多于一个的空格减少到一个 + 删除开头和结尾处的换行符,包括如果在中间且 >2 则减少到两个

转载 作者:行者123 更新时间:2023-12-01 03:39:50 25 4
gpt4 key购买 nike

我需要右/左 trim 字符串,将中间的多个空格减少到一个......但排除换行符。这就是我尝试过的:

var trimMessageTest = varMessageTest.replace(/^\s+|\s+$/g,'');      // Trim whitespace left & right
var newMessageTest = trimMessageTest.replace(/(?:(?!\n\r)\s\s+)/g,' '); // Reduce whitespace and exclude line break
//var newMessageTest = trimMessageTest.replace(/\s\s+/g,' '); // Reduce whitespace
console.log(newMessageTest);

最后一步删除开头和结尾的换行符...并将多个换行符 if > 2 ...减少为两个换行符,如下所示:

var lastMessageTest = newMessageTest.replace(/((?:\r\n?|\n)+)$|(?:\r\n?|\n){2,}/g, function ($0,$1) {
return $1 ? '' : '\n\n';
});
console.log(newMessageTest);

满足此要求的最佳方法是什么?

最佳答案

我会使用一个简单的函数:

function cleanupText(text) {
return text && text // Ensure text exists
.trim() // Trim left and right spaces
.replace(/\n{2,}/g, '\n\n') // Replace 2+ linebreaks with 2 ones
.replace(/ +/g, ' '); // Replace consecutive spaces with one
}

片段

Use ECMAScript 6 (ES6) compatible browser (not IE) to run snippet as code use template literals delimited by backticks:

"use strict";

function cleanupText(text) {
return text && text // Ensure text exists
.trim() // Trim left and right spaces
.replace(/\n{2,}/g, '\n\n') // Replace 2+ linebreaks with 2 ones
.replace(/ +/g, ' '); // Replace consecutive spaces with one
}

const sampleText = `
Lorem Ipsum is simply dummy text of the printing and typesetting industry.

Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.




It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages,


and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

`;

// Cleanup text
console.log(cleanupText(sampleText));

关于javascript - 正则表达式 - 右/左 trim + 将中间多于一个的空格减少到一个 + 删除开头和结尾处的换行符,包括如果在中间且 >2 则减少到两个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43983645/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com