M
M
Muranx2020-04-24 06:04:01
JavaScript
Muranx, 2020-04-24 06:04:01

Why doesn't the regular expression work in this example?

Hello !
Can you tell me what will be the result of executing this code in this case? kidding . . . The task is next. . . I have several blocks in which, with the help, I need to replace something with something, in fact, everything almost turned out, however, for some reason unknown to me, some regular expressions do not work at all, more precisely, regular expressions are slightly more complex than ordinary words enclosed in . . .
console.log( this ) ;
divregExp/. . ./

<div class="any">function agg(){return true}</div><br>
<div class="any">function yt(x){return x.toUpperCase()}</div><br>
<div class="any">function (t, y, z){return "hello"}</div><br>
<div class="any">function hello(n){return Math.sqrt(n)}</div><br>
<div class="any">function h32(){console.log(false)}</div><br>

let test = document.querySelectorAll('.any');

let regCon = {
  '/function/' : '<span style="color: red">',
  '/return/' : '<span style="color: orange">',
  '/console(?=\.)/' : '<span style="color: purple">',
  // '/(?<=function\s)\w+(?=\()/' : '<span style="color: blue">', // ВОТ ЭТА СТРОКА
};

for(let k=0; k<test.length; k++){
    for(let o in regCon){
        test[k].innerHTML = test[k].innerHTML.replace(new RegExp(eval(o), 'gim'), m => regCon[o]+m+'</span>');
    };
};

T . e . if you uncomment the line ВОТ ЭТА СТРОКА, then the script does not work correctly, ALTHOUGH regExp101.comthis ' regular season ' works absolutely correctly! I ask for your help in explaining this case! Well, if suddenly, the answer will be so simple that you just have to replace some index in the cycle, or put an extra comma somewhere, if it’s not difficult for you, say a few words about the implementation, I mean the principle itself, what is an object whose key is a regular expression, and the value is what we will replace with, and of course, working with a cycle, in general, your competent (i hope) opinion! Thank you !

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Sokolov, 2020-04-24
@Muranx

If you open the browser console, there will be an error due to the commented line: "invalid regexp group"
At least in my FireFox.
Because FireFox doesn't support such fancy regular expressions as look-behind (?<= ). IE, Safari too.
And it would be nice to remove eval()and slash in the keys regCon:

'function' : '<span style="color: red">',
// ...
new RegExp(o, 'gim')

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question