微信小程序常用wxs轮子
小程序编写中经常用到的一些工具轮子函数
文章目录
内容过长进行裁切
var sliceStr = function (str, len) {
var len = len || 8;
if (str != null) {
if (str.length > len) {
return str.substring(0, len) + "...";
} else {
return str;
}
}
return '';
}
高亮显示
var highLight = function (content, key, res) {
if (res == undefined) {
res = [];
}
key = key.toUpperCase();
var keyLen = key.length;
var tmp = content.toUpperCase();
if (tmp.length >= keyLen && keyLen > 0) {
var index = -1;
index = tmp.indexOf(key);
if (index != -1) {
var n = content.substring(0, index);
res.push({
type: 2,
text: n
});
var y = content.substring(index, index + keyLen);
res.push({
type: 1,
text: y
});
content = content.substring(index + keyLen, content.length);
highLight(content, key, res);
} else {
res.push({
type: 2,
text: content
});
}
} else {
res.push({
type: 2,
text: content
});
}
return res;
}
空格转义
var myReplace = function (content) {
content = content.replace(" ", " ");
if (content.indexOf(" ") != -1) {
return myReplace(content);
}
return content;
}
分隔展位号
var splitStand = function (str) {
if (!str) {
return [];
}
var arr = str.split(',');
if (arr.length <= 2) {
return arr;
}
return [arr[0], arr[1], '...'];
}
分隔字符串
var split = function (str) {
if (!str) {
return [];
}
return str.split(',');
}
判断数组中是否存在某个元素,也可用于字符串的判断(可替换indexOf[微信小程序标签内不支持indexOf,需要自己定义])
var contain = function (arr, str) {
return arr.indexOf(str) > -1;
}
导出
module.exports.myReplace = myReplace;
module.exports.highLight = highLight;
module.exports.sliceStr = sliceStr;
module.exports.split = split;
module.exports.splitStand = splitStand;
module.exports.contain = contain;
使用
- 将以上方法保存到util.wxs文件内
- 在需要使用是页面进行引入,如意路径层级
<wxs src="../../wxs/util.wxs" module="util"></wxs>
- 调用:
<!-- 以http开头走外链,否则 走本系统内链接 -->
<navigator url="{{util.contain(item.path,'http')?'/pages/webview/index?url='+item.path:item.path}}">
<view class="bg hw60 tc-block icon-{{item.icon}}"></view>
<text class="text textColor textFz">{{item.name}}</text>
</navigator>