javascript - Regex replace with captured -
this question has answer here:
i want replace non alphanumeric character in string self surrender "[" , "]".
i tried this:
var text = "ab!@1b*. ef"; var regex = /\w/g; var result = text.replace(regex, "[$0]"); console.log(result);
i expecting get:
ab[!][@]1b[*][.][ ]ef
but instead get:
ab[$0][$0]1b[$0][$0][$0]ef
how can using javascript(node)?
you need wrap group in parentheses assign $1, this:
var text = "ab!@1b*. ef"; var regex = /(\w)/g; var result = text.replace(regex, "[$1]"); console.log(result);
wiki
Comments
Post a Comment