仅替换句子开头和结尾处的空格

Jef*_*har 0 javascript regex

有谁知道如何使用正则表达式和 javascript 将字符串开头和结尾的空格替换为  

例子:

`   Hello World. The white spaces in between the sentence should not be replaced. Only the start and end should be replaced with &nbsp.   `
Run Code Online (Sandbox Code Playgroud)

更换后:

`   Hello World. The white spaces in between the sentence should not be replaced. Only the start and end should be replaced with &nbsp.   `
Run Code Online (Sandbox Code Playgroud)

Cod*_*iac 5

您需要首先捕获space并且比在替换的回调函数中您可以添加 no。基于 比赛长度。

  • ^\s+- 匹配字符串开头的空格。
  • |- 交替与逻辑或相同。
  • \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 &nbsp.   `

let op = str.replace(/^\s+|\s+$/g, function(match){
  return ` `.repeat(match.length)
})

console.log(op)
Run Code Online (Sandbox Code Playgroud)