ShittyAdvice
ShittyAdvice

Reputation: 265

How can I get the first and last word using regex

I know with regex you can get every word and their first letter with:

/\b(\w)/g,

But is there also a way to get the first word?(I tried a lot of googling but couldnt find any that did both instead of either first or last word) I believe it should be possible to get both in 1 regex instead of 2 different ones.

A example for my string and wanted result?

String: Hello Mister world

Would give back: ['H', 'w']

Upvotes: 0

Views: 8698

Answers (3)

ssube
ssube

Reputation: 48247

While it will only handle fairly specific inputs, you should be able to use something like:

var test = [
  "Get the first and last word",
  "Hello world!",
  "foo bar",
  "this is a test, for matches",
  "test"
];

var rex = /^((\w*)\s?).*?(\s?(\w*)[^\w\s]*)$/;

test.forEach(function(it) {
  document.getElementById("results").textContent += JSON.stringify(rex.exec(it)) + "\n";
});
<pre id="results"></pre>

Matches 2 and 4 will give you the trimmed versions of the first and last words.

Broken down, the regex /^((\w*)\s?).*?(\s?(\w*)[^\w\s]*)$/:

  1. Match the first sequence of word characters, optionally followed by whitespace (match 1 is the full sequence, match 2 excludes the trailing whitespace character).
  2. Match some of anything, but leave room for the final word match.
  3. Match another optional whitespace character, then some word characters, then anything else (presumably punctuation) (match 3 is the full sequence, match 4 excludes the leading whitespace and trailing punctuation)

Upvotes: 0

1252748
1252748

Reputation: 15362

^(\w).*\b(\w).*?$

will give you what you're looking for. regex101

Upvotes: 0

vks
vks

Reputation: 67968

^\w|\b\w(?=\S+$)

Try this.See demo.

https://regex101.com/r/fA6wE2/31

Edit:

^\s*(\w)|\b(\w)(?=\S+$)

Use this and grab the group or capture if there are spaces at start.

Upvotes: 2

Related Questions