Javascript 角度过滤器将所有下划线替换为空格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31939288/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 07:25:40  来源:igfitidea点击:

Angular filter to replace all underscores to spaces

javascriptregexangularjsangularjs-filter

提问by Ayeye Brazo

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

我需要一个过滤器来将字符串中的所有下划线替换为空格

回答by Avinash Raj

string.replacenot only accepts string as first argument but also it accepts regex as first argument. So put _within regex delimiters /and aslo add gmodifier along with that. gcalled global modifier which will do the replacement globally.

string.replace不仅接受字符串作为第一个参数,还接受正则表达式作为第一个参数。因此,请放入_正则表达式分隔符/并同时添加 g修饰符。g称为全局修饰符,它将在全局范围内进行替换。

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

回答by John Rix

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:

在您的 HTML 中按如下方式使用它:

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

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

小注意:to由于 Angular 内容安全规则,参数中的任何 HTML 标签都会导致表达式失败。

回答by Damien C

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

在某些情况下,您可以使用split()函数。
.replace 函数不符合正则表达式语法(即.replace(/,/g,'\n')语法)

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

完整语法:
{{myVar.toString().split(',').join('\n')}}

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

.toString()函数是在 myVar 没有在打字稿中输入为 String 的情况下使用的。

回答by Avellino

This simple function can do it:

这个简单的函数可以做到:

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

回答by BratisLatas

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.

我希望它可以帮助一个简单的改变,如果你想在更多的地方改变,使用过滤器。

回答by Aliahmad Pasa

this is i used in angularjs 1.4.7

这是我在 angularjs 1.4.7 中使用的

<li ng-show="filter.degree.length"> 
    <label>Search by Degree :- </label> {{
        filter.degree.toString().split('|').join(', ')
    }} 
</li>