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.