1

I've been handed a JS regex function that is run on a form to correctly brand products on a page.

I'm rebuilding the page using angularJS and need to similarly apply that regex as each product name is output but I'm unsure how best to do this...

so I am writing out the products in my ng-repeat simply as {{product.name}} but how can I apply this branding ruleset to this output...

The following regex checks for branding pattern and applies a html style as needed:

var regex = /(Brand1|Brand2) ([-\w\s+]+)([™®])/
val = val.replace(regex, "$1 <strong>$2$3</strong>");

It may help if I post the full JS as it does a sense check first to see if TM or (R) is in the product name in which case the branding check/regex should be used.

if (val.indexOf('™') !== -1 || val.indexOf('®') !== -1) {

            // Check for exceptions
            if (val.indexOf('Special BRAND 1') !== -1 || val.indexOf('Special BRAND 2') !== -1) {

                val = val.replace("Special BRAND 1™", "Special BRAND <strong>1&trade;</strong>");
                val = val.replace("Special Brand 2™", "Special Brand <strong>2&trade;</strong>");

            } else {

                /*  The products not an exception so run regex
                */

                var regex = /(Brand1|Brand2) ([-\w\s+]+)([™®])/

                val = val.replace(regex, "$1 <strong>$2$3</strong>");

            }

        }
1
  • Sorry - so the question is how do I apply that branding rule to the angular value I am writing out Commented Jun 3, 2015 at 12:18

1 Answer 1

1

A custom filter can be a good solution.

angular.module('yourModule').filter('brandRegex', function() {
    return function(val) {
        //do whatever you want to do and return the changed value
    };
});

In your HTML:

{{product.name | brandRegex}}
Sign up to request clarification or add additional context in comments.

2 Comments

That is a thing of beauty thanks! That being said I am getting a branded output however any text wrapped in a strong tag is writing the literal strong in angular brackets out...
that can also be solved, but it's a little more complicated since you want to inject html tags into your html code. you can achieve this with ng-bind-html, which requires you to include angular-sanitize as a resource. here's a simple example: plnkr.co/edit/Kv96xIdwW22KNMuXfQan?p=preview

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.