Q:

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;
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:
`&nbsp;&nbsp;&nbsp;Hello World. The white spaces in between the sentence should not be replaced. Only the start and end should be replaced with &nbsp.&nbsp;&nbsp;&nbsp;`

A:

You need to first capture the space and than in callback function of replace you can add the no. of &nbsp; based on length of match.

^\s+ - Matches spaces at the start of string.
| - Alternation same as logical OR.
\s+$ - Matches spaces at the end of string

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 `&nbsp;`.repeat(match.length)
})

console.log(op)

