找出一个句子中最长的单词 - Javascript [英] Find out the longest word from a sentence - Javascript

查看:85
本文介绍了找出一个句子中最长的单词 - Javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么方法可以找出Javascript中最长的单词吗?它应该忽略标点符号!



我理解逻辑,但代码...叹息



以下是我们所做的 -


  1. 计算在一起的字母数字字符的数量,空格或任何符号。

  2. / li>
  3. 返回单词的最大长度。

希望我明确自己。 。

解决方案

拆分字符串,遍历零件并追踪最长的一个。



类似这样:

  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); 

工作jsfiddle


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 -

  1. Count the number of alphanumeric characters that are together, not separated by a space or any sign.

  2. Get their lengths.

  3. Find the biggest length in all.
  4. 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);

Working jsfiddle

这篇关于找出一个句子中最长的单词 - Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆