Angular filter to replace all underscores to spaces

前端 未结 6 1341
感动是毒
感动是毒 2020-12-18 18:10

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

相关标签:
6条回答
  • 2020-12-18 18:35

    This simple function can do it:

    public getCleanedString(cadena) {
        cadena = cadena.replace(/_/g, ' ');
        return cadena;
      }
    
    0 讨论(0)
  • 2020-12-18 18:37

    this is i used in angularjs 1.4.7

    <li ng-show="filter.degree.length"> 
        <label>Search by Degree :- </label> {{
            filter.degree.toString().split('|').join(', ')
        }} 
    </li>
    
    0 讨论(0)
  • 2020-12-18 18:50

    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.

    0 讨论(0)
  • 2020-12-18 18:50

    There is a easyer method:

    You could replace it inline without a defined filter. This is the way.

    This example its for replace just in the view.

    {{ value.replace(/_/g, ' ') }}
    

    I hope its could help in a simple change, if you want to change in more places, use the filter.

    0 讨论(0)
  • 2020-12-18 18:52

    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, ' ');
      };
    });
    
    0 讨论(0)
  • 2020-12-18 18:56

    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.

    0 讨论(0)
提交回复
热议问题