从HTML标记

时间:2017-11-02 18:06:09

标签: jquery

我有这个HTML代码。

<a href="sample?ie=UTF8&amp;p=IDXYZ0123&amp;usecaseSessionID=64657491001" id="sample-link">TZX   (IDXYZ0123)</a>

我想提取id&#34; IDXYZ0123&#34;由此。此ID将括在()括号中。

4 个答案:

答案 0 :(得分:1)

所以到目前为止你还没有尝试过任何东西,只是希望我们为你做这项工作? 无论如何,只是因为它如此简单,你走了:

console.log($('#sample-link').text().match(/\(([^]+)\)/)[1]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="sample?ie=UTF8&amp;p=IDXYZ0123&amp;usecaseSessionID=64657491001" id="sample-link">TZX   (IDXYZ0123)</a>

然而,使用jQuery对此来说真是太过分了 - 它可以用纯JS来完成:

console.log(document.getElementById('sample-link').textContent.match(/\(([^]+)\)/)[1]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="sample?ie=UTF8&amp;p=IDXYZ0123&amp;usecaseSessionID=64657491001" id="sample-link">TZX   (IDXYZ0123)</a>

答案 1 :(得分:1)

假设您想从链接文本而不是href获取它,并且ID将始终位于括号之间,您可以这样做:

&#13;
&#13;
$(function() {
  var linkText = $('#sample-link').text(),
      start_pos = linkText.indexOf('(') + 1,
      end_pos = linkText.indexOf(')',start_pos),
      ID = linkText.substring(start_pos,end_pos);
      
  console.log('ID: ' + ID);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="sample?ie=UTF8&amp;p=IDXYZ0123&amp;usecaseSessionID=64657491001" id="sample-link">TZX   (IDXYZ0123)</a>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

&#13;
&#13;
var test_str=$('#sample-link').html();
test_str=test_str.substring(test_str.lastIndexOf("(")+1,test_str.lastIndexOf(")"));

console.log(test_str);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>


<a href="sample?ie=UTF8&amp;p=IDXYZ0123&amp;usecaseSessionID=64657491001" id="sample-link">TZX   (IDXYZ0123)</a>
&#13;
&#13;
&#13;

答案 3 :(得分:0)

要使用txt2re.com的正则表达式获取ID号:

&#13;
&#13;
$(document).ready(function(){
   var txt =  $("#sample-link").text();
    //from txt2re.com
    var re1='.*?';	// Non-greedy match on filler
    var re2='((?:[a-z][a-z]*[0-9]+[a-z0-9]*))';	// Alphanum 1

    var p = new RegExp(re1+re2,["i"]);
    var m = p.exec(txt);
    if (m !== null)
    {
        var id=m[1];
        $("#result").text(id);
    }
    
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


  <body>
    <a href="sample?ie=UTF8&amp;p=IDXYZ0123&amp;usecaseSessionID=64657491001" id="sample-link">TZX   (IDXYZ0123)</a>
    <div>
    <span>id:</span>
    <span id="result"></span>
    </div>
  </body>
&#13;
&#13;
&#13;