+ 3
Please I want to access a variable in regex js. I tried the regex constructor to no avail.
I was trying to recursively find a text in a DOM tree. It worked but I want the regex to accept the text parameter. More info can be found in the code for your perusal. https://code.sololearn.com/cQRitttxIB8B/?ref=app
9 Antworten
+ 2
to use text parameter as a regex expression, you need to use the regex constructor... but you also need to escape all characters wich have special meaning in a regex expression (ie: dot '.' brackets -- at least '([)]' but maybe '{}' -- escape char '\' and so on... perhaps all ASCII char except alphanumerics and space /[^\w ]/ could be a good safe choice -- that need to be tested)...
in addition it would be more efficient to pass the regex expression instead of the text to the function to avoid building the regex at each function call (recursive iteration) ^^
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp
+ 1
visph hello. Please I'm stuck with this. Could you help me out?
+ 1
visph thanks a million bro!!! 😀😀😀😀😀😀😀. Thanks ☺️ ☺️ ☺️ ☺️
+ 1
visph bro, I tried the constructor and still it didn't work. It matched other stuff except for what I wanted.
+ 1
visph i wrote it like this
let pattern = new RegExp(text, "gi" ) ;
if(node.nodeValue.match(pattern)) {...}
+ 1
visph the constructor didn't work for the recursive function but for non-recursive cases, it worked
+ 1
recursive function doesn't work because you pass the recursive function to the forEach method, while it expect a specific function signature...
[...node.childNodes].forEach(findText)
should be:
[...node.childNodes].forEach(node => findText(node,text))
forEach callback signature expect as arguments: value, index, array... so your version get node index as text parameter ;P
+ 1
visph aha I see. I thought the text parameter won't be needed when the node has children that's why I just passed the callback to it which obviously has the first parameter as the child node of the forEach. I'll try this 😁😁😁.
Thank you.
+ 1
visph It worked bro! 🤩🤩🤩🤩🤩🤩🤩🤩🤩🤩🤩. I'm super excited! Thanks so much 😁😁😁😁😁😁🤓🤓🤓🤓🎉🎉🎉🎉🎉