javascript 在一个字符串中查找最长的单词,并使用regex [closed]

k4ymrczo  于 2023-05-05  发布在  Java
关注(0)|答案(1)|浏览(157)

已关闭,此问题为opinion-based。目前不接受答复。
**想改善这个问题吗?**更新问题,以便editing this post可以用事实和引用来回答。

2天前关闭。
Improve this question

function findLongestWordLength(str) {
  
  //Creating the regex and adding the solution in the array
  let word = [];
  let regex = /[A-Za-z]+\S/g;
  let result = str.match(regex);
  word.push(result);
  
  //Iterating the array using forEach
  let currentWord = 0;
  word.forEach((element) => {
    element.forEach((element2) => {
      let longestWord = element2.length;
      if (currentWord < longestWord) {
        currentWord = longestWord;
      }
    });
  });
  
  //It returns the longest word (the length of that word)
  return currentWord;
}

console.log(
  findLongestWordLength("The quick brown fox jumped over the lazy dogs")
);

这是你在JavaScript中解决这个问题的最短方法吗?它可以用更少的代码行来编写吗?或者更像一行代码,使用数组方法,如map,filter或reduce?另外,是否有更短/更简单的regEx可以用于将字符串拆分为单词?

xnifntxz

xnifntxz1#

稍微短一点,返回最长的单词:

const findLongestWord = str => str.split(/\W{1,}/)
  .reduce((a, c) => c.length > a.length ? c : a, '');

console.log(findLongestWord(`I am a lonely pilgrim searching 
for stackoverflowishness in the wildermark.`));
// => stackoverflowishness

或者,如果你只想要最长单词的长度(你的主题说最长单词,但你的代码说最长单词长度):

const findLongestWordLength = str => str.split(/\W{1,}/)
  .reduce((a, c) => c.length > a.length ? c : a, '').length;

console.log(findLongestWordLength(`I am a lonely pilgrim searching 
for stackoverflowishness in the wildermark.`)); // => 20

相关问题