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 => 0output 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 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 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:
great
ReplyDelete