Reputation: 265
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
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]*)$/
:
Upvotes: 0
Reputation: 15362
^(\w).*\b(\w).*?$
will give you what you're looking for. regex101
Upvotes: 0
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