Finding the longest word in a string using JavaScript

Jangidrahulkumar
2 min readDec 23, 2020

--

Hello guys in this tutorial, we are going to learn how finding the longest word in a string using JavaScript.

There are many way to find longest word in a string but we can use for this solution, we will use the Array.prototype.reduce().

The reduce() method applies a function against an accumulator and each value of the array (from left-to-right) to reduce it to a single value.

reduce() executes a callback function once for each element present in the array. You can provide an initial value as the second argument to reduce, here we will add an empty string “ ”.

Finding the longest word step 1:

Add below code inside index.html
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8" />
<title>Finding the longest word in a string using JavaScript</title>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0" />
<meta http-equiv=”X-UA-Compatible” content=”ie=edge” />
<link rel=”stylesheet” href=”style.css” />
</head>
<body>
<div class=”center-center”>
<span>( Finding the longest word in a string using JavaScript )</span>
<h1 id=”string”>Stack Findover is the largest, most trusted online community for developers</h1>
<button id=”string_check” onclick=”onbtnclick()”>Click me</button>
</div>
<script type=”text/javascript”>
function onbtnclick() {
document.getElementById(“string_check”).disabled = true;

const str = document.getElementById(“string”).textContent;
const findLongest = (str = ‘’) => {
const strArr = str.split(‘ ‘);
const word = strArr.reduce((acc, val) => {
let { length: len } = acc;
if(val.length > len){
acc = val;
};
return acc;
}, ‘’);
return word;
};
function matchString() {
var string = str;
var result = string.match(findLongest(str));
document.getElementById(‘string’).innerHTML = ‘Output: ‘+’{ ‘ +result+ ‘ }’;
} matchString()
}
</script>
</body>
</html>

Read Full Article

--

--

Jangidrahulkumar

Hii i'm Rahul Jangir, a tech geek, designing enthusiast and an online expert could be a graduate in technology who is addicted to front-end development.