Kmspico Download | Official KMS Activator Website [New Version 2024] Uw betrouwbare online apotheek Drogisterij Unique in Nederland Vavada вход позволяет мгновенно попасть в мир азартных игр и бонусов! Получи доступ и начни выигрывать прямо сейчас.

How to get first two words of a string in JavaScript?

You can get the first two words of a string in JavaScript using the `split()` method and array slicing. Here’s an example:

Example:

function getFirstTwoWords(str) {
let words = str.trim().split(/\s+/); // Split by spaces, handling multiple spaces
return words.slice(0, 2).join(" "); // Get first two words and join them back
}

// Test cases
console.log(getFirstTwoWords("Hello World from JavaScript")); // Output: "Hello World"
console.log(getFirstTwoWords(" JavaScript is awesome ")); // Output: "JavaScript is"
console.log(getFirstTwoWords("SingleWord")); // Output: "SingleWord"
console.log(getFirstTwoWords("")); // Output: ""

Explanation:

1. `trim()` removes leading/trailing spaces.
2. `split(/\s+/)` splits the string into words using one or more spaces as separators.
3. `slice(0, 2)` extracts the first two words.
4. `join(” “)` combines them back into a string.

This method handles multiple spaces, empty strings, and single-word cases properly.