regex - JavaScript expressions and replacement rules -


i new js expressions , task asks me replace string in expression.

use regular expressions apply following replacement rules on string:

a => 4  e => 3  o => 0  

output result of applying expressions string ‘leet haxxor’.

my attempts okay or off mile.

pattern = /[a 4] [e 3] [o 0]/; pattern = /[a > 4] [e > 3] [o > 0]/;  console.log(pattern.test("l33t h4xx0r")); false 

really need explanation of how can replaced yet exist in expression?

i'd suggest:

var replacewith = {     a: '4',     e: '3',     o: '0', };  var str = "leet haxxor",     output = str.replace(/a|e|o/g, function(char){         return replacewith[char];     });  console.log(output); // l33t h4xx0r 

js fiddle demo.

the regular expression matches characters a or (|) e or o anywhere in string (using g modifier/switch following regular expression's closing). function uses found character (char) retrieve replacement character replacewith object.

as felix notes, in comments, /a|e|o/ can, indeed, replaced [aeo], give:

var replacewith = {     a: '4',     e: '3',     o: '0', };  var str = "leet haxxor",     output = str.replace(/[aeo]/g, function(char){         return replacewith[char];     });  console.log(output); // l33t h4xx0r 

js fiddle demo.

the changed approach defines characters changed if listed, or range (for example [a-e] find characters a e inclusive), rather verbose approach using | operator.

references:


Comments

Post a Comment

Popular posts from this blog

php - regexp cyrillic filename not matches -

c# - OpenXML hanging while writing elements -

python - Scapy Dot11ReassoReq -