Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,900 questions

51,831 answers

573 users

How to find the length of the shortest word in a string with JavaScript

2 Answers

0 votes
function findShortestWordLength(s) {
    let words = s.split(' ');
    let shortLength = Number.MAX_SAFE_INTEGER;
  
    for (let i = 0; i < words.length; i++) {
      	if (words[i].length < shortLength) {
        	shortLength = words[i].length;
      	}
    }

    return shortLength;
  }
  
  
const len = findShortestWordLength("JavaScript is ECMAScript specification programming language");

console.log(len);


  
    
    
/*
run:

2
    
*/

 



answered Sep 15, 2021 by avibootz
edited 20 hours ago by avibootz
0 votes
function shortestWordLength(text) {
    if (!text || text.trim().length === 0) {
        return 0;
    }

    // Split on any whitespace (spaces, tabs, newlines)
    const words = text.trim().split(/\s+/);

    let minLen = Infinity;

    for (const word of words) {
        const len = word.length;
        if (len < minLen) {
            minLen = len;
        }
    }

    return minLen === Infinity ? 0 : minLen;
}

function main() {
    const text = "Find the shortest word length in this string";

    const result = shortestWordLength(text);

    console.log("Shortest word length:", result);
}

main();




/*
run:

Shortest word length: 2

*/

 



answered 20 hours ago by avibootz
...