Angular filter to replace all underscores to spaces Angular filter to replace all underscores to spaces javascript javascript

Angular filter to replace all underscores to spaces


string.replace not only accepts string as first argument but also it accepts regex as first argument. So put _ within regex delimiters / and aslo add g modifier along with that. g called global modifier which will do the replacement globally.

App.filter('underscoreless', function () {  return function (input) {      return input.replace(/_/g, ' ');  };});


Here's a generic replace filter alternative

App.filter('strReplace', function () {  return function (input, from, to) {    input = input || '';    from = from || '';    to = to || '';    return input.replace(new RegExp(from, 'g'), to);  };});

Use it as follows in your HTML:

{{ addText | strReplace:'_':' ' }}

Minor note: Any HTML tags in the to parameter will cause the expression to fail due to Angular content security rules.


In some case, you can use split() function.
.replace function is not compliant with regexp syntax (i.e. .replace(/,/g,'\n') syntax)

Full syntax:
{{myVar.toString().split(',').join('\n')}}

.toString() function is in case myVar is not typed as String in typescript.