简体   繁体   中英

Format / filter an output with regular expression in Angular.js

Given this:

        <span ng-repeat="extra in extras">
            <br>
            <input type="checkbox" ng-click="addExtra()"  value="{{extra.id}}" >{{extra.name}} - <strong>{{extra.real_price}}</strong>
        </span>

How do i make the {{extra.real_price}} to output only numbers using filters ?

Example: extra.real_price being 'from 400€' to transform to '400'

you can use a regexp to strip out all characters except numeric ones:

app.filter('onlyNumbers', function () {
    return function (item) {
      return item.replace(/[^\d|^,|^.]/g, '');
    }
  });

The regexp can be read: replace all characters not being a number, nor a comma nor a point.

Note that, as you are using currency values, both point and comma should be accepted values.

These are some examples of usage and output:

{{ '23345€' | onlyNumbers }}       => 23345
{{ '$23345' | onlyNumbers }}       => 23345
{{ '$23345.00' | onlyNumbers }}    => 23345.00
{{ '23345,00 €' | onlyNumbers }}   => 23345,00

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM