settingsAccountsettings
Menusettings

Q: Expression Split - JavaScript task

+3 votes

Write a JS function that splits a passed in JS code into separate parts.

The passed in code will always have one or more spaces between operators and operands. Normal brackets (‘(‘,’)’), commas (,), semicolons (;) and the member access operator (‘.’(dot), as in “console.log”) should also be used for splitting.
String literals will always be initialized with double quotes (") and will contain only letters. Make sure there are no empty entries in the output.

The input comes as a single string argument - the JS code that has to be split.

Examples:

Input:
'let sum = 4 * 4,b = "wow";'

Output:
let
sum
=
4
*
4
let
b
=
"wow"


Input:
'let sum = 1 + 2;if(sum > 2){\tconsole.log(sum);}'

Output:
let
sum
=
1
+
2
if
sum
>
2
{
console
log
sum
}


The output should be printed on the console, with each elements obtained from the split is printed on a new line.

asked in JavaScript category by user sam

1 Answer

+1 vote

Here is the javascript anser and solution code (see line 2 for the regular expression used as a pattern):

function exSplit(input) {
    let pattern = /[\s\.();,]+/;
    let result = input.split(pattern)
        .join("\n");
    console.log(result);
}

exSplit('let sum = 4 * 4,b = "wow";');

 

answered by user samfred5830
edited by user golearnweb
...