Angular filter to replace all underscores to spaces
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;
}
Related videos on Youtube
Ayeye Brazo
Updated on February 28, 2020Comments
-
Ayeye Brazo about 4 years
I need a filter to replace all the underscores to spaces in a string
-
Max over 8 yearsThis fail if
input
isn't a string, or ifinput
is null or undefined. -
Avinash Raj over 8 yearssimple, just use an if stmt for condition checking.
-
mediaguru about 6 yearsBratisLatas I liked your method, however it appears to only replace only one instance, not multiple.
-
jjmontes about 6 yearsI 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 over 5 yearsWhat question are you answering? They want to replace underscore with space.
-
Sujay U N over 5 yearsWhere shud I add App.filter code ? and Which version of angular is this..
-
John Rix over 5 yearsThis 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 over 4 yearsThis is the perfect answer, simple and optimized.
-
Himanshu S Shankhala about 4 yearsWorks well for single character replacement