Abbreviate string and put point -Explanations

Hi coders,
I found this exercise on CodeWars on how to abbreviate a string and insert a dot in the initials.
While looking for a solution I came across that there is a match () method with the following regular expressions (
I absolutely didn’t know how to solve it and the only solutions that came to mind was to scroll through the string and take the first value as an index, but I didn’t know how to take the index of the initial of the last name)


var user = "Sam Harris"
var matches = user.match(/\b(\w)/g);  // this 
var abbrevation = matches.join(".");   // this 
console.log(abbrevation);


I asked first if my reasoning without looking at the solution on the Internet was fine and how does that regular expression translate?

\b Matches a word boundary (position between a word character non-word character).
() A capturing group. Saves any matching (sub)string for later use
\w Matches a word character
g (at the end) global flag

So the entire regex matches and captures each word character that appears at a word boundary. For example, the first letter at the start of a first and last name.

var abbrevation = matches.join(".");   // this 

String.match(regex) (mdn) returns an array (or null), in this example assigned to the matches name. Array.join (mdn) combines array elements into a string with the provided string “.” between each.

Assuming that’s the sort of explanation you were looking for, I would suggest taking a look at the FCC Regular Expressions curriculum

1 Like

Thanks it was very exhaustive!!!
what does it correspond to / at the beginning of expression?
Because I tried to search but I didn’t find anything about it :thinking:

The start and end of a string are each treated as word/non-word boundaries. So the ‘S’ in “Sam Harris” matches because it is at the start of the string.

1 Like