瀏覽代碼

feat: 工具函数新增从url获取参数的方法

cuiyalong 1 年之前
父節點
當前提交
2e907cf852
共有 1 個文件被更改,包括 36 次插入0 次删除
  1. 36 0
      packages/util/modules/format/str.js

+ 36 - 0
packages/util/modules/format/str.js

@@ -64,3 +64,39 @@ export function replaceKeyword(
     return value.replace(regExp, newChar)
   }
 }
+
+/**
+ * 从key=value&key1=value1&key2=value2...中获取key值
+ * @param {String} formString 目标字符串,必须为key=value&key1=value1的格式
+ * @param {String} targetKey 要从目标字符串获取哪个key
+ * @returns {String}
+ */
+export function getFormValue(formString, targetKey) {
+  let reg = new RegExp('(^|&)' + targetKey + '=([^&]*)(&|$)', 'i')
+  let r = formString.match(reg) //获取url中'?'符后的字符串并正则匹配
+
+  let context = ''
+  if (r != null) context = r[2]
+  // 释放变量
+  reg = null
+  r = null
+  return context == null || context == '' || context == 'undefined' ? '' : context
+}
+
+/**
+ * 从url中获取对应name的参数
+ * @param {String} name 
+ * @returns {String}
+ */
+export function getQueryParam(name) {
+  const search = window.location.search
+  let target = ''
+  if (search) {
+    const arr = search.split('?')
+    if (arr[1]) {
+      target = arr[1]
+    }
+  }
+  const value = getFormValue(target, name)
+  return decodeURIComponent(value)
+}