1

This is my angularjs filter :

app.filter('cleanit', function() {
    return function (input) {
        input = input.replace(new RegExp('é'),'é');
        input = input.replace(new RegExp('É'),'É');
        input = input.replace(new RegExp('Ô'),'Ô');
        input = input.replace(new RegExp('''), '\'');
        return input;
    }
});

I use it for replace bad accents in feeds parsed with Google Feed API. It's works good but it's only works once per item, the replacement no longer takes place then, after the first success. what's wrong ?

3
  • 2
    You need to add the g modifier to your RegExps to make it global. You can also do this using /regex/g syntax instead of using the new RegExp() constructor because your regexes are statically defined. Commented Aug 28, 2014 at 13:19
  • 1
    Actually now that I think about it, why are you even using RegExp for your replace? If you just pass a string as the first argument, it automatically uses a global replace, and you're not replacing anything that requires a regex. Commented Aug 28, 2014 at 13:26
  • Take a look at angular-regex-filter, maybe it suits you. Commented Oct 6, 2014 at 18:24

1 Answer 1

4

As RevanProdigalKnight commented, you need to specify g modifier to globally replace matches:

input = input.replace(new RegExp('é', 'g'), 'é');

input = input.replace(/é/g, 'é');

BTW, here's a different way to solve your problem (instead of specifying charref, using replacement function.)

input = input.replace(/&#x([a-f0-9]+);/ig, function($0, $1) {
    // The return value is used as a replacement string
    return String.fromCharCode(parseInt($1, 16));
});
Sign up to request clarification or add additional context in comments.

2 Comments

In the new RegExp() constructor the flags argument is also a string, so it should be new RegExp('regex', 'g')
@RevanProdigalKnight, You're right. Thank you for pointing that. I updated the code accordingly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.