1

I am trying to format a MAC address in a table that is populated using AngularJS:

<tr ng-repeat="dev in devices">
<td>{{dev.mac.replace(/(.{2})/g,"$1:")}}</td>
</tr>

{{dev.mac}} works just fine (aside from being unformatted), but when I add the .replace() function it breaks. I tried escaping the forward slash based on the error I received, which didn't help. Is .replace() not available inside the browser or is there a different syntax for regex inside the double braces or what am I doing wrong?

The goal is to convert AABBCCDDEEFF into AA:BB:CC:DD:EE:FF as easily as possible within the double braces. As a bonus question, how do I prevent the trailing ':' in the regex (it currently prints AA:BB:CC:DD:EE:FF:)?

Edit: Adding the error message

Error: $parse:syntax Syntax Error

Syntax Error: Token '/' not a primary expression at column 20 of the expression [dev.mac.replace(/(.{2})/g,"$&:")] starting at [/(.{2})/g,"$&:"].

That seems to indicate the forward slash is causing the problem, but like I said, escaping it doesn't help.

3
  • Is it due to the limiting quantifier? Try <td>{{dev.mac.replace(/../g,"$&:")}}</td> Commented Dec 20, 2018 at 19:42
  • I get the same result changing '1' to '&'. I'm updating this post to include the error I get from the browser. Commented Dec 20, 2018 at 19:47
  • Use this: dev.mac.replace(new RegExp('(..)(..)(..)(..)(..)(..)'), '$1:$2:$3:$4:$5:$6') inside the curly braces. Commented Dec 20, 2018 at 20:08

1 Answer 1

1

Rather than running your replace inline like that, it'd be better to abstract that out into a function, that should fix any issues you're having with it not getting interpreted correctly. This article shows the right syntax for declaring a function on the scope to call here: function call inside Angular double curly braces, it should be something like this

$scope.fixMacAddress = function(addr)
{
   return addr.replace(/(.{2})/g,"$1:")
}

and

{{ fixMacAddress(dev.mac) }}
Sign up to request clarification or add additional context in comments.

2 Comments

Well that's definitely a solid workaround, hadn't thought going the function route since I was just thinking inline. I'm going to wait before selecting this as the answer in case I do get an inline solution, but if there's a reason inline isn't an option this will be the answer. Also, thanks for not just assuming I already knew how to declare a function inside $scope (I'm well versed, but it's always appreciated to be explicit like that).
@JWAspin Sounds good, yeah angular's documentation is a bit of a beast so it's always best err on the side of overexplaining when it comes to angular

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.