简体   繁体   English

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

[英]Replace white spaces only at the beginning and end of a sentence

Does anyone know how to replace white spaces in the beginning and end of the string with &nbsp using regular expression and javascript; 有谁知道如何使用正则表达式和javascript用&nbsp替换字符串开头和结尾的空格;

Example: 例:

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

After replacing: 更换后:

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

You need to first capture the space and than in callback function of replace you can add the no. 您需要首先捕获space然后在replace的回调函数中可以添加no。 of     based on length of match. 根据比赛的长度。

  • ^\\s+ - Matches spaces at the start of string. ^\\s+ -匹配字符串开头的空格。
  • | - Alternation same as logical OR. -与逻辑或相同。
  • \\s+$ - Matches spaces at the end of string \\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) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM