'Regular Expression to search longest word in a string
I have a string:
var str = "Lorem ipsum dolor sit amet, consectetur adipiscing elit";
Is there a way to find the longest word in a string using regex? This will prevent me to split the string into words and then looping through all of them.
Possibly if I can use it in JavaScript as:
str.search(/regex/); // should return 28 (position of word 'consectetur')
Thanks.
Solution 1:[1]
As already mentioned in comments, this is not possible with a regex only solution. And nearly all solutions I can think of; would still need you to slice the string to words. The smallest solution you can use would be:
var x = str.match( /\w+/g );
var y = x.map( function(t) { return t.length } );
var z = str.indexOf( x[y.indexOf( Math.max.apply(Math, y) )] );
Solution 2:[2]
Check this Update LINK
JS Code:
var str = "Lorem ipsum dolor sit amet, consectetur adipiscing elit";
str = str.replace(/[^A-Za-z\s]/g, " ");
var maxoffset = 0, maxlen=0, wordoffset = 0;
for (var i = 0; i < str.length; i++) {
if (str[i] == " ") {
wordoffset = i + 1;
}
if (i - wordoffset + 1> maxlen) {
maxoffset = wordoffset;
maxlen = i - wordoffset + 1;
}
}
return str.substring(maxoffset, maxoffset + maxlen);
Solution 3:[3]
I know this is old, but here is my solution that I did not see posted.
Obv this is the fastest solution posted, albeit a little late.
Accomplish the task using Array.prototype.reduce with String.prototype.match.
text.match(/\w+/g).reduce( (p,c) =>
c.length > p.length ? c : p
,'');
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | SVK |
Solution 3 |