settingsAccountsettings
Menusettings

Q: Match All Words in JavaScript (task)

+2 votes

Write JavaScript function that matches all words in a text, a word is anything that consists of letters, numbers or underscores (_).

The input comes as single string argument – the text from which to extract the words.

Examples:

Input:
'A Regular Expression needs to have the global flag in order to match all occurrences in the text'

Output:

A|Regular|Expression|needs|to|have|the|global|flag|in|order|to|match|all|occurrences|in|the|text

Input:
'_(Underscores) are also word characters'

Output:
_|Underscores|are|also|word|characters


The output should be printed on the console and should consist of all words concatenated with a “|“(pipe), check the examples bellow to better understand the format.

asked in JavaScript category by user golearnweb
edited by user golearnweb

1 Answer

+1 vote

Use regex (read more here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions)

The solution (see line 2 (line 3 also works just fine)):

function matchWords(str) {
    let pattern = /([a-zA-Z-0-9_]+)/g;
    //or //let patternTwo = /\w+/g;

    console.log(str.match(pattern).join("|"));
}

matchWords('A Regular Expression needs to have the global flag in order to match all occurrences in the text');

 

answered by user hues
edited by user golearnweb
...