Angular filter to replace all underscores to spaces
Angular filter to replace all underscores to spaces
I need a filter to replace all the underscores to spaces in a string
4 Answers
4
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.
string.replace
_
/
g
g
App.filter('underscoreless', function ()
return function (input)
return input.replace(/_/g, ' ');
;
);
input
input
simple, just use an if stmt for condition checking.
– Avinash Raj
Feb 19 '16 at 5:15
Here's a generic replace filter alternative
App.filter('strReplace', function ()
return function (input, from, to) ;
);
Use it as follows in your HTML:
strReplace:'_':' '
Minor note: Any HTML tags in the to
parameter will cause the expression to fail due to Angular content security rules.
to
great ans. works perfect for any replcement
– Jinna Balu
Feb 21 '17 at 4:54
Where shud I add App.filter code ? and Which version of angular is this..
– Sujay U N
Jan 22 at 7:11
This 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']);
– John Rix
Jan 22 at 13:03
App
var App = angular.module('myApp', ['some-dependency', 'some-other-dependency']);
This simple function can do it:
public getCleanedString(cadena)
cadena = cadena.replace(/_/g, ' ');
return cadena;
What question are you answering? They want to replace underscore with space.
– Toto
Sep 13 '18 at 10:42
I already corrected it
– Avellino
Sep 13 '18 at 11:05
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.
BratisLatas I liked your method, however it appears to only replace only one instance, not multiple.
– mediaguru
Feb 21 '18 at 18:50
I 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
.– jjmontes
May 9 '18 at 14:09
syntax Error: Token '/' not a primary expression
Thanks for contributing an answer to Stack Overflow!
But avoid …
To learn more, see our tips on writing great answers.
Required, but never shown
Required, but never shown
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
This fail if
input
isn't a string, or ifinput
is null or undefined.– Max
Oct 16 '15 at 3:20