有没有人知道如何用正则表达式和javascript替换字符串开头和结尾的空格;
示例:
` Hello World. The white spaces in between the sentence should not be replaced. Only the start and end should be replaced with  . `替换后:
` Hello World. The white spaces in between the sentence should not be replaced. Only the start and end should be replaced with  . `发布于 2019-02-05 08:09:50
首先需要捕获space,而不是在回调函数中替换,您可以添加no。基于匹配长度的 。
^\s+ -匹配字符串开头的空格。| -与逻辑OR相同的替换.\s+$ -匹配字符串末尾的空格
let str = ` Hello World. The white spaces in between the sentence should not be replaced. Only the start and end should be replaced with  . `
let op = str.replace(/^\s+|\s+$/g, function(match){
return ` `.repeat(match.length)
})
console.log(op)
https://stackoverflow.com/questions/54530012
复制相似问题