Home > Blockchain >  How to remove function name and open and close parentheses in JavaScript?
How to remove function name and open and close parentheses in JavaScript?

Time:01-29

How to remove a wrapping function using Regex in JavaScript? Say I have

parse(someVar)

I want only someVar to be left. I saw this post but not sure how to apply it.

CodePudding user response:

Taken from here:

Function names can contain letters, digits, underscores, and dollar signs (same rules as variables).

Which, in RegEx, looks like this:

[a-zA-Z\d_$] 

So to match the function call you specified, it would look like this (I added parenthesis around the someVar / input parameter, so we can extract it later as a RegEx group):

[a-zA-Z\d_$] \(([a-zA-Z\d_$] )\)

And in JavaScript, we can take the someVar value out like this:

const regex = /[a-zA-Z\d_$] \(([a-zA-Z\d_$] )\)/;

const paramName = regex.exec("parse(someVar)")[1];

console.log(paramName);
// Outputs "someVar"

CodePudding user response:

You can also achieve this with the help of String.match() method along with the Array.map() method.

Live Demo :

console.log("parse(someVar)".match(/\((.*?)\)/g).map(b => b.replace(/\(|(.*?)\)/g,"$1")))

RegEx explanation :

Match string regex - \((.*?)\)

\( - To allow opening parenthesis
(.*?) - Group which define one or more characters, ? denotes not mandatory (So there might be a characters inside parenthesis or might not be)
\) - To allow closing parenthesis

CodePudding user response:

here is a working solution:

let str = "parse(someVar)";

let result = str.replace(/^\w \((.*)\)$/, "$1");

console.log(result);

  • Related