代码之家  ›  专栏  ›  技术社区  ›  Sireini

在特定值之后获取字符串的一部分

  •  0
  • Sireini  · 技术社区  · 6 年前

    我试图得到一个字符串的一部分这就是字符串:

    "#" id="fs_facebook-btn" data-count="facebook" onclick="window.open('https://www.facebook.com/sharer/sharer.php?u=http%3A%2F%2Fsharebtns.fingerspitz.nl.ebox%2F', '_blank', 'scrollbars=0, resizable=1, menubar=0, left=100, top=100, width=550, height=440, toolbar=0, status=0');return false" title="Share on Facebook"
    

    我想买 data-count 价值观这就是我所尝试的:

    for (var i = 0; i < s.length; i++) {
        console.log(s[i]);
        console.log(s[i].substring(0, s[i].indexOf('data-count="')));
    }
    

    但是它停在了我想要得到的部分,我怎样才能得到数据计数的值呢?

    2 回复  |  直到 6 年前
        1
  •  1
  •   fdomn-m    6 年前

    继续使用 .indexOf .substring :

    var s = '"#" id="fs_facebook-btn" data-count="facebook" onclick=...';
    
    var searchFor = 'data-count="';
    
    var startPos = s.indexOf(searchFor) + searchFor.length;  // add on the length to get the end
    var endPos = s.indexOf('"', startPos);        // find the next " after data-count=
    
    alert(s.substring(startPos, endPos));         // extract the string

    另一种方法是让jquery 解析 对您来说,即使html以字符串开头,您也可以通过包装将其转换为jquery对象 <div .. > ,例如:

    var s = '"#" id="fs_facebook-btn" data-count="facebook" onclick=...';
    alert($("<div " + s + "></div>").data("count"))
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

    虽然代码稍微少一些,但如果要解析的字符串太多(10000+),则速度会慢一些。

        2
  •  0
  •   hsz    6 年前

    您可以尝试用空白分隔此字符串,然后使用 find 把它清理干净 replace :

    s.split(' ').find(v => v.contains('data-count')).replace(/.*?"([^"]+")/, '$1')
    

    或者在最后被 = 并移除 " 字符:

    s.split(' ').find(v => v.contains('data-count')).split('=')[1].replace(/"/g, '')