settingsAccountsettings
By using our mini forum, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy
Menusettings

Q: Find Variable Names in Sentences in JavaScript

+2 votes

Write a JavaScript function that finds all variable names in a given string. A variable name starts with an underscore (“_”) and contains only Capital and Non-Capital English Alphabet letters and digits. Extract only their names, without the underscore. Try to do this only with regular expressions.

The input comes as single string, on which you have to perform the matching.

Examples:

Input:
The _id and _age variables are both integers.

Output:
id,age


Input:
Calculate the _area of the _perfectRectangle object.

Output:
area,perfectRectangle


Input:
__invalidVariable _evenMoreInvalidVariable_ _validVariable

Output:
validVariable


The output consists of all variable names, extracted and printed on a single line, each separated by a comma.

asked in JavaScript category by user eiorgert

1 Answer

+1 vote

Here si my solution. Note line #3 - with the regex (the core of the solution):

function findVar(input) {

    let pattern = /\b(_)([a-zA-Z0-9]+)\b/g;

    console.log(input
        .match(pattern)
        .join(",")
        .replace(/_/g,""));
}

findVar("The _id and _age variables are both integers.");
//findVar("Calculate the _area of the _perfectRectangle object.");
//findVar("__invalidVariable _evenMoreInvalidVariable_ _validVariable");

 

answered by user hues
...