Skip to content

Instantly share code, notes, and snippets.

@Samuell1
Last active June 16, 2021 16:20
Show Gist options
  • Save Samuell1/a2751d1ec6ecff0c8eead092ea14a636 to your computer and use it in GitHub Desktop.
Save Samuell1/a2751d1ec6ecff0c8eead092ea14a636 to your computer and use it in GitHub Desktop.
Simple filters for VueJs 2
import Vue from 'vue'
// Truncate
Vue.filter('truncate', function (text, length = 30, clamp = '...') {
if (text.length <= length) {
return text
} else {
return text.substring(0, length) + clamp
}
})
// Uppercase
Vue.filter('uppercase', function (value) {
return (value || value === 0)
? value.toString().toUpperCase()
: ''
})
// Lowercase
Vue.filter('lowercase', function (value) {
return (value || value === 0)
? value.toString().toLowerCase()
: ''
})
// Capitalize
Vue.filter('capitalize', function (value) {
if (!value && value !== 0) return ''
value = value.toString()
return value.charAt(0).toUpperCase() + value.slice(1)
})
// Currency
Vue.filter('currency', function (value, currency = 'EUR', decimals = 2) {
const digitsRE = /(\d{3})(?=\d)/g
value = parseFloat(value)
if (!isFinite(value) || (!value && value !== 0)) return ''
const stringified = Math.abs(value).toFixed(decimals)
const _int = decimals
? stringified.slice(0, -1 - decimals)
: stringified
const i = _int.length % 3
const head = i > 0
? (_int.slice(0, i) + (_int.length > 3 ? ',' : ''))
: ''
const _float = decimals
? stringified.slice(-1 - decimals)
: ''
const sign = value < 0 ? '-' : ''
return sign + head +
_int.slice(i).replace(digitsRE, '$1,') +
_float + ' ' +
currency
})
// Comma
Vue.filter('comma', function (value) {
return value
? `${value}, `
: ''
})
// Placeholder
Vue.filter('placeholder', function (value, placeholder) {
return value || placeholder || ''
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment