【问题标题】:How to create a function to split the following string? [duplicate]如何创建一个函数来拆分以下字符串? [复制]
【发布时间】:2021-03-25 20:53:12
【问题描述】:

我有这个字符串

"G_ENABLED_IDPS=app; COOKIE_EINF=someCookie; _ga=someGA;
_hjid=someHJID; _gcl_au=someglcau; COOKIE_EINF_SESS=somecookie1; _gid=somegid; _hjIncludedInPageviewSample=2; _hjTLDTest=3; _hjAbsoluteSessionInProgress=0; _hjIncludedInSessionSample=1; _gat_UA-124355-12=5"

我需要某种函数来给split这个字符串提供一个参数,例如假设我的字符串是text

text.split(";") ,将其拆分为一个以";"分隔的数组

但我需要这样的功能

returnText(text , property) 会像这样工作

returnText(text, "_gcl_au") --> returns "someglcau"

【问题讨论】:

  • 也看看this。只需将答案中的document.cookie 替换为text 即可。

标签: javascript


【解决方案1】:

您实际上可以在这里使用正则表达式替换方法,作为单行选项:

function returnText(text, property) {
    var term = text.replace(new RegExp("^.*\\b" + property + "=([^;]+)\\b.*$", "gm"), "$1");
    return term;
}

var input = "G_ENABLED_IDPS=app; COOKIE_EINF=someCookie;_ga=someGA;_hjid=someHJID; _gcl_au=someglcau; COOKIE_EINF_SESS=somecookie1; _gid=somegid; _hjIncludedInPageviewSample=2; _hjTLDTest=3; _hjAbsoluteSessionInProgress=0; _hjIncludedInSessionSample=1; _gat_UA-124355-12=5";
console.log(returnText(input, "_gcl_au"));

【讨论】:

    【解决方案2】:

    您可以使用拆分,就像您尝试过的那样:

    function returnText(text , property){
        entries = text.split('; ');
        const newEntries = [];
        entries.forEach(item => {
           let vals = item.split('=');
           newEntries[vals[0]] = vals[1]
        });
        return newEntries[property];
    }
        
    const text = "G_ENABLED_IDPS=app; COOKIE_EINF=someCookie; _ga=someGA;_hjid=someHJID; _gcl_au=someglcau; COOKIE_EINF_SESS=somecookie1; _gid=somegid; _hjIncludedInPageviewSample=2; _hjTLDTest=3; _hjAbsoluteSessionInProgress=0; _hjIncludedInSessionSample=1; _gat_UA-124355-12=5";
    console.log(returnText(text,'_gcl_au'));

    【讨论】:

      猜你喜欢
      • 2017-03-30
      • 1970-01-01
      • 2012-09-05
      • 2018-06-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-09
      相关资源
      最近更新 更多