2

I want to replace (javascript) all chars that not in regex pattern with '_' Example

string: #he57/h

Pattern: /^[_a-zA-Z][_a-zA-Z0-9]*$/

Expected result: _he57_h

I tried

var str = "#he57/h";
var res = str.replace(/^[^_a-zA-Z][^_a-zA-Z0-9]*$/g, "_");
console.log(res);

But its not do the work.

req res
  • 69
  • 5
  • Well, @AlexK was right, you really need to replace each non-word char with `_` in this case. Use `str.replace(/\W/g, '_')`. At least it seems so. Else, use https://jsfiddle.net/5fox81bw/ that is a generic solution. – Wiktor Stribiżew Aug 02 '17 at 16:30
  • if looking for a general solution, it is here: https://stackoverflow.com/questions/22118657/replace-part-of-string-that-doesnt-match-regex – Kaddath Aug 02 '17 at 16:31
  • Thanks, I will check it. Can you please add some explanation on your solution and why my example didnt work? – req res Aug 02 '17 at 16:32
  • Your second character is an alpha character. `[^a-zA-Z0-9]` would find any non alphanumerical character. See https://regex101.com/r/fcqDzk/1/ for longer explanation. – chris85 Aug 02 '17 at 17:06

0 Answers0