Hello guys in this tutorial, we are going to learn how to find 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 “ ”.
[].reduce(function(previousValue, currentValue) {...}, “”);
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>
<h2 id="string">Stack Findover is the largest, most trusted online community for developers</h2>
<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>
Finding the longest word step 2:
Then we need to add code for style.css which code I provide the below screen.
* {
padding: 0;
margin: 0;
font-family: 'IBM Plex Sans', sans-serif;
}
body {
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
background: #f1f2f3;
}
h1#string {
color: #0f62fe;
font-size: 20px;
font-weight: 600;
}
span {
color: #FF5722;
display: block;
margin: 20px 0;
font-size: 18px;
}
button {
background-color: #0f62fe;
border: 1px solid transparent;
color: #fff;
cursor: pointer;
padding: 10px 20px;
display: block;
font-size: 18px;
width: 100%;
text-align: center;
outline: 0;
margin-top: 20px;
}
.center-center {
max-width: 500px;
margin: auto;
position: relative;
}
.center-center:before {
content: "{";
position: absolute;
top: 0;
left: -100px;
font-size: 180px;
display: block;
color: #0f62fe;
}
.center-center:after {
content: "}";
position: absolute;
top: 0;
right: -100px;
font-size: 180px;
display: block;
color: #0f62fe;
}
Finding the longest word Video output:
Finding the longest word codepn output:
For more interesting content
Top comments (0)