我需要一个过滤器来将字符串中的所有下划线替换为空格。
我需要一个过滤器来将字符串中的所有下划线替换为空格。
我需要一个过滤器来将字符串中的所有下划线替换为空格。
string.replace
不仅接受字符串作为第一个参数,还可以接受正则表达式作为第一个参数。因此,将_
放在正则表达式分隔符/
中,并添加g
修饰符。g
称为全局修饰符,将在全局范围内进行替换。
App.filter('underscoreless', function () {
return function (input) {
return input.replace(/_/g, ' ');
};
});
这里是一个通用的替换过滤器替代方案。
App.filter('strReplace', function () {
return function (input, from, to) {
input = input || '';
from = from || '';
to = to || '';
return input.replace(new RegExp(from, 'g'), to);
};
});
在你的HTML中按如下方式使用:
{{ addText | strReplace:'_':' ' }}
小提示:任何在to
参数中的HTML标签会导致表达式失败,这是由于Angular内容安全规则引起的。
App
表示从创建Angular应用程序后返回的对象,如下所示:var App = angular.module('myApp', ['some-dependency', 'some-other-dependency']);
- John Rix在某些情况下,您可以使用split()
函数。
.replace函数不符合正则表达式语法(即.replace(/,/g,'\n')
语法)
完整语法:
{{myVar.toString().split(',').join('\n')}}
.toString()
函数适用于myVar在Typescript中未被定义为字符串类型的情况。
public getCleanedString(cadena) {
cadena = cadena.replace(/_/g, ' ');
return cadena;
}
有一种更简单的方法:
您可以在不定义过滤器的情况下替换它。这就是方法。
此示例仅用于在视图中进行替换。
{{ value.replace(/_/g, ' ') }}
这是我在 AngularJS 1.4.7 中使用的
<li ng-show="filter.degree.length">
<label>Search by Degree :- </label> {{
filter.degree.toString().split('|').join(', ')
}}
</li>
input
不是字符串,或者input
为 null 或未定义,则会失败。 - Max