1

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);

4
  • So what is the problem? Do you mean you want to get KeCh as a result? Commented Nov 28, 2019 at 9:40
  • @WiktorStribiżew can do this by only RegEx ? only need KC Commented Nov 28, 2019 at 9:41
  • You can't unless you use .replace. Something like s.replace(/[^]*?\b(\w)\w*\W+(\w)[^]*|[^]+/, '$1$2') Commented Nov 28, 2019 at 9:42
  • @WiktorStribiżew Yes this is what i am looking for only RegEx Thank you Commented Nov 28, 2019 at 9:46

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Which one is best using RegEx with replace or joining with substring ?
@JayVaghasiya Multiple matches + joining is very clear/readable/maintainable and is thus preferable.
0

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);

1 Comment

Only need KC and using only RegEx
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.