Home > Back-end >  How to remove whitespaces in a regular expression using match?
How to remove whitespaces in a regular expression using match?

Time:08-07

I am trying to remove whitespaces before and after the string using a regular expression in javascript. One solution is to replace all the whitespace with nothing. I thought of a different solution, match all non whitespace characters before and after the string (I matched 1 whitespace in between the words). For some reason it is not working and the result still includes the spaces. Any help would be appreciated!

let hello = "   Hello, World!  ";
let wsRegex = /(?<=\s*)\S*\s\S*/g; // Change this line
let result = hello.match(wsRegex); // Change this line

console.log(result);

CodePudding user response:

Please use String#replace:

var repl = str.replace(/^\s |\s $|\s (?=\s)/g, "");

If using match

let result = hello.match(/\S /g); 

CodePudding user response:

You can use named groups to just get the string without starting and trailing white spaces.

Here is an example modifying you code:

let hello = "   Hello, World!     ";
let wsRegex = /^\s*(?<hello>. \S)\s*$/m; // Change this line
let result = hello.match(wsRegex)?.groups?.hello; // Change this line

console.log(result);
  • Related