折腾:
【未解决】小程序中的js实现字符串的去除首尾空格
期间,想要把一些相对通用的函数,比如trim,放到全局的地方,比如util,helper之类,使得所有页面都能调用的到。
突然自己发现:
微信自带模板中,都有个util.js了:

然后看看别处如何调用
全局搜一下:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 | const formatTime = date = > { const year = date.getFullYear() ... return [year, month, day]. map (formatNumber).join( '/' ) + ' ' + [hour, minute, second]. map (formatNumber).join( ':' ) } const formatNumber = n = > { n = n.toString() return n[ 1 ] ? n : '0' + n } module.exports = { formatTime: formatTime } |


看到用法了:
1 2 3 4 | //logs .js const util = require( '../../utils/util.js' ) return util.formatTime(new Date(log)) |
自己去照葫芦画瓢试试
【总结】
最后用代码:
util/util.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | const formatTime = date = > { const year = date.getFullYear() const month = date.getMonth() + 1 const day = date.getDate() const hour = date.getHours() const minute = date.getMinutes() const second = date.getSeconds() return [year, month, day]. map (formatNumber).join( '/' ) + ' ' + [hour, minute, second]. map (formatNumber).join( ':' ) } const formatNumber = n = > { n = n.toString() return n[ 1 ] ? n : '0' + n } const trim = originStr = > { var trimmedStr = originStr.replace( / (^\s * )|(\s * $) / g, "") console.log( "trim: %s -> %s" , originStr, trimmedStr) return trimmedStr } module.exports = { formatTime: formatTime, trim: trim, } |

其他地方调用:
pages/index/index.js
1 2 3 4 5 | const util = require( '../../utils/util.js' ) var trimmedInput = util.trim(this.data.curInputValue) console.log( "trimmedInput=%s" , trimmedInput) |
是可以实现util全局函数的效果的,运行也没问题:

转载请注明:在路上 » 【已解决】小程序中如何实现全局的工具或帮助函数