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

时间:2019-02-05 08:06:05

标签: javascript regex

有人知道如何使用正则表达式和javascript;用&nbsp替换字符串开头和结尾的空格吗?

示例:

`   Hello World. The white spaces in between the sentence should not be replaced. Only the start and end should be replaced with &nbsp.   `

更换后:

`   Hello World. The white spaces in between the sentence should not be replaced. Only the start and end should be replaced with &nbsp.   `

1 个答案:

答案 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 &nbsp.   `

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

console.log(op)