首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >仅在句首和句尾替换空格

仅在句首和句尾替换空格
EN

Stack Overflow用户
提问于 2019-02-05 08:06:04
回答 1查看 359关注 0票数 0

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

示例:

代码语言:javascript
运行
复制
`   Hello World. The white spaces in between the sentence should not be replaced. Only the start and end should be replaced with &nbsp.   `

替换后:

代码语言:javascript
运行
复制
`   Hello World. The white spaces in between the sentence should not be replaced. Only the start and end should be replaced with &nbsp.   `
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-02-05 08:09:50

首先需要捕获space,而不是在回调函数中替换,您可以添加no。基于匹配长度的 

  • ^\s+ -匹配字符串开头的空格。
  • | -与逻辑OR相同的替换.
  • \s+$ -匹配字符串末尾的空格

代码语言:javascript
运行
复制
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)

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54530012

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档