Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable with reg expression is not recognized in js

I am trying to generate a template using slush, my code repo is here: https://github.com/NaveenDK/slush-template-generator/blob/master/templates/react-native-app/MediaButtons.js

Even though the template files run fine on its own, when I try to generate using slush with the following lines in the MediaButtons.js file

 let match = /\.(\w+)$/.exec(filename);
    let type = match ? `image/${match[1]}` : `image`;

I get an error which says that 'match' is not defined, when I scaffold it with slush and when it is in the templates folder . My guess is that the reg expression is not interpreted properly

Thanks for any help! Naveen

like image 924
Naveen DINUSHKA Avatar asked Jan 13 '18 02:01

Naveen DINUSHKA


People also ask

Can we pass variable in regular expression in JavaScript?

yes of course you can pass a variable in regular expression wait i will show the example of an email Id regular expression…

Why regex is not working?

You regex doesn't work, because you're matching the beginning of the line, followed by one or more word-characters (doesn't matter if you use the non-capturing group (?:…) here or not), followed by any characters.

Can you use variables in regular expressions?

In a regular expression, variable values are created by parenthetical statements.

How do you evaluate a regular expression in JavaScript?

JavaScript | RegExp test() Method The RegExp test() Method in JavaScript is used to test for match in a string. If there is a match this method returns true else it returns false. Where str is the string to be searched. This is required field.


1 Answers

When you generate with Slush, your code is changed (minimized or whatever you are asking it to do) but the literal templates are not. So at runtime the variable match is not declared anymore but still you access it while evaluating type's literal value. And an error is raised.

When you do not generate with Slush, your code is unchanged and works.

To avoid this issue, change to this:

let match = /\.(\w+)$/.exec(filename);
let type = match ? 'image/'+match[1] : 'image';
like image 79
RaphaMex Avatar answered Oct 16 '22 06:10

RaphaMex