JavaScript 如何找到字符串中的最长单词
在本文中,我们需要给定一个字符串,任务是使用 JavaScript 找到字符串中最长的单词。
示例:
Input: "This is a demo String find the largest word from it"
Output: "largest"
Input: "Hello guys this is geeksforgeeks where students learn programming"
Output: "geeksforgeeks"
为了实现这一点,我们使用以下方法:
1. 使用 正则表达式 和 for循环 。
2. 使用 split() 和 sort() 方法。
3. 使用 split() 和 reduce() 方法。
4. 使用 split() 方法和 for循环 。
方法1:使用正则表达式和for循环
在这种方法中,我们使用正则表达式 /[a-zA-Z0-9]+/gi 将字符串拆分成一个单词数组,然后使用for循环遍历数组并搜索最长的字符串。
示例: 这个示例使用了上述解释的方法。
<script>
// Javascript program to search largest word from a string
function longest(str){
// Split the string using regex
str = str.match(/[a-zA-Z0-9]+/gi);
// Creating a empty string to store largest word
let largest = "";
// Creating a for...loop to iterate over the array
for(let i = 0; i < str.length; i++){
// If the i'th item is greater than largest string
// then overwrite the largest string with the i'th value
if(str[i].length > largest.length){
largest = str[i]
}
}
return largest;
}
console.log(longest("Hello guys this is geeksforgeeks where"+
" students learn programming"))
</script>
输出:
"geeksforgeeks"
方法2:通过使用 split() 和 sort() 方法
在此方法中,我们使用 String.split() 方法拆分字符串,并使用 Array.sort() 方法对数组进行排序。
示例: 此示例使用上述解释的方法。
<script>
function longest(str){
// Split the string into array
str = str.split(" ")
// Return the first sorted item of the Array
return str.sort((a, b) => b.length - a.length)[0]
}
console.log(longest("Hello guys this is geeksforgeeks"+
" where students learn programming"))
</script>
输出:
"geeksforgeeks"
方法3:使用 split() 和 reduce() 方法
在这种方法中,我们将使用String.split()方法分割字符串,并通过使用reduce()方法搜索数组中的最大元素,即你的最长字符串。
示例: 此示例使用上述说明的方法。
<script>
function longest(str){
// Split the string into array
str = str.split(" ");
// Get the index of largest item of the array
let index = str.reduce((acc, curr, i)=>{
if(curr.length > str[acc].length){
return i
}
return acc;
}, 0)
return str[index];
}
console.log(longest("Hello guys this is geeksforgeeks"+
" where students learn programming"))
</script>
输出:
"geeksforgeeks"
方法4:使用split()和for…循环
在这种方法中,我们将拆分字符串并在此之前,我们将声明一个空字符串以便将最长字符串的结果存储在其中。此外,我们将使用箭头函数,并且整个任务将在其下执行。
示例: 此示例使用上述方法进行解释。
<script>
// JavaScript code to for the above approach..
let longestWord = (string) => {
let stringg = string.split(" ");
let longest = 0;
let longest_word = null;
for (let i = 0; i < stringg.length; i++) {
if (longest < stringg[i].length) {
longest = stringg[i].length;
longest_word = stringg[i];
}
}
return longest_word;
};
console.log(
longestWord(
"Hello guys this is geeksforgeeks where students learn programming"
)
);
</script>
输出:
geeksforgeeks
极客教程