1.词条中变量替换值
在字符串中可能存在变量,需要替换值,可以使用这种办法。
在国际化中因为需求需要把一句拆开来展示,这时中英文显示顺序不一致,可以使用这种办法。
/**
* @param textTemplate 词条模板
* @param replaceObject 需要被替换成的真是数据
*/
const i18nReplace = (textTemplate:string, replaceObject:object) => {
const subRegRex = /\{\s*([^\|\}]+?)\s*(?:\|([^\}]*))?\s*\}/g;
return textTemplate.replace ? textTemplate.replace(subRegRex, (match, key) => {
return textTemplate[key] !== undefined ? replaceObject[key] : match;
}) : textTemplate;
}
console.log(i18nReplace('你好{0}', { 0: 'vue' }));
// 你好vue
2.获取url参数
/**
* 获取url参数
* @param name 参数名
* @param urlStr 要匹配的地址,默认不传
*/
const getQueryString = (name: string, urlStr?: string) => {
const reg = new RegExp('(^|&)' + name + '=([^&]*)(