有人知道如何使用正则表达式和javascript;用&nbsp替换字符串开头和结尾的空格吗?
示例:
` 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  . `
答案 0 :(得分:4)
您需要首先捕获space
,然后在replace的回调函数中可以添加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)