I have a 16 digit property that comes back for example(1234123412341234). I would like it to render on my UI with a space every 4 number characters for example(1234 1234 1234 1234). I'm using Angular JS so I'm looking for a way to accomplish this. I'm pretty sure it's either a custom Angular filter or regex related, but my knowledge of either and how to implement it is limited.
You can use a regex with lookahead.
The Positive Lookahead looks for the pattern after the equal sign, but does not include it in the match.
x(?=y)
Matches 'x' only if 'x' is followed by 'y'. This is called a lookahead.
For example,
/Jack(?=Sprat)/
matches 'Jack' only if it is followed by 'Sprat'./Jack(?=Sprat|Frost)/
matches 'Jack' only if it is followed by 'Sprat' or 'Frost'. However, neither 'Sprat' nor 'Frost' is part of the match results.
function format(s) { return s.toString().replace(/\\d{4}(?=.)/g, '$& '); } console.log(format(1234123412341234));
You can use match()
and then join()
with a whitespace.
var str = '1234123412341234'; var res = str.match(/.{1,4}/g).join(' '); console.log(res);
AngularJS filter is easy to setup. Just accept one parameter and apply any JS formatting on it. Here is a working example:
var app = angular.module('myApp', []); app.filter('myFilter', function() { return function(x) { return x.toString().replace(/\\d{4}(?=.)/g, '$& '); // your format filter here }; }); app.controller('demoCtrl', function($scope) { $scope.test = 1234123412341234; });
<!DOCTYPE html> <html> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script> <body> <div ng-app="myApp" ng-controller="demoCtrl"> {{test | myFilter}} </div> </body> </html>
(I took regex code from Nina Scholz 's answer. Feel free to use any other regex)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.