找出一个句子中最长的单词 - Javascript [英] Find out the longest word from a sentence - Javascript
问题描述
我理解逻辑,但代码...叹息
以下是我们所做的 -
-
计算在一起的字母数字字符的数量,空格或任何符号。
/ li> - 返回单词的最大长度。
希望我明确自己。 。
拆分字符串,遍历零件并追踪最长的一个。
类似这样:
var parts = sentence.split();
var longestIndex = -1;
var longestWord = 0; (零件[i] .length> longestWord){
longestWord = parts [ I]。长度;
longestIndex = i;
alert(最长的单词是+ parts [longestIndex] +:+ longestWord +characters);
如果您需要分割非字母字符以及空格,则需要使用正则表达式。你可以改变这一行:
var parts = sentence.split();
为此(感谢Kooilnc的正则表达式):
var parts = sentence.match(/ \ w [az] {0,} / gi);
Is there any way to find out the longest word in Javascript? It should ignore punctuation marks too!
I understood the logic, but the code... sigh
Here's what we do -
Count the number of alphanumeric characters that are together, not separated by a space or any sign.
Get their lengths.
- Find the biggest length in all.
- Return the word with the biggest length.
Hope I'm making myself clear...
Split the string, loop over the parts and keep track of the longest one.
Something like this:
var parts = sentence.split();
var longestIndex = -1;
var longestWord = 0;
for(var i=0; i < parts.length; i++){
if(parts[i].length > longestWord){
longestWord = parts[i].length;
longestIndex = i;
}
}
alert("longest word is " + parts[longestIndex] + ": " + longestWord + " characters");
If you need to split on non alphabetic characters as well as spaces you need to use regexes. You can change this line:
var parts = sentence.split();
To this (thanks Kooilnc for the regex):
var parts = sentence.match(/\w[a-z]{0,}/gi);
这篇关于找出一个句子中最长的单词 - Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!