0

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:

`   Hello World. The white spaces in between the sentence should not be replaced. Only the start and end should be replaced with &nbsp.   `
  • 1
    Possible duplicate of [How to replace all occurrences of a string in JavaScript](https://stackoverflow.com/questions/1144783/how-to-replace-all-occurrences-of-a-string-in-javascript) – Salek Feb 05 '19 at 08:09

1 Answers1

4

You need to first capture the space and than in callback function of replace you can add the no. of   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 ` `.repeat(match.length)
})

console.log(op)
Code Maniac
  • 37,143
  • 5
  • 39
  • 60