I need a filter to replace all the underscores to spaces in a string
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.
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']);
–
Incuse 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.
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.
syntax Error: Token '/' not a primary expression
. –
Placenta This simple function can do it:
public getCleanedString(cadena) {
cadena = cadena.replace(/_/g, ' ');
return cadena;
}
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>
© 2022 - 2024 — McMap. All rights reserved.
input
isn't a string, or ifinput
is null or undefined. – Pewter