Angular filter to replace all underscores to spaces

76,146

Solution 1

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, ' ');
  };
});

Solution 2

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.

Solution 3

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.

Solution 4

This simple function can do it:

public getCleanedString(cadena) {
    cadena = cadena.replace(/_/g, ' ');
    return cadena;
  }
Share:
76,146

Related videos on Youtube

Ayeye Brazo
Author by

Ayeye Brazo

Updated on February 28, 2020

Comments

  • Ayeye Brazo
    Ayeye Brazo about 4 years

    I need a filter to replace all the underscores to spaces in a string

  • Max
    Max over 8 years
    This fail if input isn't a string, or if input is null or undefined.
  • Avinash Raj
    Avinash Raj over 8 years
    simple, just use an if stmt for condition checking.
  • mediaguru
    mediaguru about 6 years
    BratisLatas I liked your method, however it appears to only replace only one instance, not multiple.
  • jjmontes
    jjmontes about 6 years
    I don't think that's a valid angular expression. It does work if the first argument is a string, but if using the regular expression, I get syntax Error: Token '/' not a primary expression.
  • Toto
    Toto over 5 years
    What question are you answering? They want to replace underscore with space.
  • Sujay U N
    Sujay U N over 5 years
    Where shud I add App.filter code ? and Which version of angular is this..
  • John Rix
    John Rix over 5 years
    This is for AngularJS 1.x. App here represents the object you get back from creating your Angular app as follows: var App = angular.module('myApp', ['some-dependency', 'some-other-dependency']);
  • Alexis
    Alexis over 4 years
    This is the perfect answer, simple and optimized.
  • Himanshu S Shankhala
    Himanshu S Shankhala about 4 years
    Works well for single character replacement