Jay
Jay

Reputation: 3107

First letter using RegEx of string in JavaScript

I have a string of full name.
From string to the first letter of every word. Can I get only two letters of first two words from string using only RegEx

Expected result is KC using only RegEx

var str = "Keanu Charles Reeves";
console.log(str);
str = str.match(/\b(\w)/g).join('').substring(0, 2);
console.log(str);

Upvotes: 1

Views: 144

Answers (3)

zjffun
zjffun

Reputation: 1243

var str = "Keanu Charles Reeves";
str = str.replace(/(\w).*? (\w).*/, "$1$2");
console.log(str);

Upvotes: 0

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626929

Your approach is best and you should stick to it.

As an educational-only alternative, you might use a solution based on a .replace method (because all matching methods will require joining multiple matches that you want to avoid, the reason being that you can't match disjoin (non-adjoining) pieces of text into a single group within one match operation):

s.replace(/[^]*?\b(\w)\w*\W+(\w)[^]*|[^]+/, '$1$2')

It matches the string up to the first word char that is captured into Group 1, matches up to the second word capturing its first word char into Group 2 and then matching all the string to the end, or - upon no match - [^]+ grabs the whole string, and replaces the whole string with Group 1 and 2 contents.

See the regex demo

Upvotes: 1

Swapnil Soni
Swapnil Soni

Reputation: 1049

As you wrote .substring(0,2) it will take only first 2 letters only just remove it and it will work

var str = "Keanu Charles Reeves";
console.log(str);
str = str.match(/\b(\w)/g).join('');
console.log(str);

Upvotes: 0

Related Questions