Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

You can use the built-in String method match() with a regular expression to find the number of spaces preceding the first character in a JavaScript string. Here's an example:

let str = "    Hello World!";
let numSpaces = str.match(/^\s*/)[0].length;
console.log(numSpaces); // outputs 4

In this example, the regular expression ^\s* matches any number of white space characters (\s*) at the beginning of the string (^). The match() method returns an array containing the matched substring(s). We access the first element of the array ([0]) and get its length to determine the number of spaces.