簡體   English   中英

僅在句子的開頭和結尾處替換空格

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

有誰知道如何使用正則表達式和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.   `

您需要首先捕獲space然后在replace的回調函數中可以添加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) 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM