如何在两个标签之间捕获字符串 [英] How to capture a string between two tags

查看:82
本文介绍了如何在两个标签之间捕获字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写一个书签,以增强我的工作流程.我的部分工作是获取要放入电子邮件中的正确信息.我喜欢JavaScript和jQuery,因此我正在研究一种使用此库使工作更轻松的方法.

I'm working on writing a bookmarklet to enhance my workflow at work. Part of my job is obtaining the correct information to be placed into an email. I love JavaScript and jQuery, so I'm working on a way to make my job easier using this library.

我正在针对一个标记特别奇怪的网站.我需要在匹配的标签标记之后和下一个标签标记之前捕获文本.奇怪的是,这就是P标签内的所有内容.我不知道为什么网站的开发人员也决定使用标签标记...我无法修改标记,因此这不是一种选择.我已经在网上搜索了所有内容,但找不到适合我的具体情况的有效技术.

I'm targeting a website that has particularly odd markup. I need to capture the text after a matched label tag, and before the next label tag. This is all, oddly enough, inside a P tag. I have no clue why the website's developer decided to use label tags either... I am unable to modify the markup, so that's not an option. I've searched all across the web and haven't been able to find a working technique for my specific situation.

我创建了一个jsFiddle来演示使用相同类型的标记和CSS尝试做的事情.我可以很容易地访问标签,并且已经使用了几种不同的方法(在小提琴中已注释掉),但是我仍然无法正确地捕获"两个标签标签之间的文本.文本最终将被置于警报中,因此我可以快速复制它.我尝试使用.nextUntil,但没有运气.

I created a jsFiddle to demonstrate what I'm trying to do using the same kind of markup and CSS. I have no problem accessing the label, and I've used a few different methods to do so (in the fiddle, commented out) but I am still unable to properly "capture" the text in between the two label tags. The text will end up being placed into an alert so I can quickly copy it. I've tried using .nextUntil but have had no luck with it.

基本上是这样的:

<label>item 1</label> Content to capture
<br><br>
<label>item 2</label> Don't capture this...

我担心我的尝试不起作用的原因是(我认为)nextUntil()尝试使用初始选择器查找下一个对象,因此它正在寻找下一个标签,而不是中间的文本.我试过使用$('selector').parent().nextUntil('label'),它也没有用.

I fear the reason my attempts aren't working is because (I think) nextUntil() tries to find the next object using the initial selector, so it's looking for the next label, rather than the text in between. I've tried using $('selector').parent().nextUntil('label') which also hasn't worked.

这是工作示例:

$(document).ready(function(){
  //$('p label:eq(0)')afterUntil('<br>').css('color', 'red');
  //$('p').find($('label:contains("item 1")')).nextUntil("<label>").css('color', 'red');
  $('p label:contains("item 1")').parent().nextUntil('label').css('color','red');
});

label {
  display:inline-block;    
  width:25%;
  font-weight:bold;
}
p {
  font-family:arial;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<p>
  <label>item 1</label> Capture me!<br><br>
  <label>item 2</label> Don't capture me
</p>

(小提琴: http://jsfiddle.net/1c2LpzrL/1/ )

(fiddle: http://jsfiddle.net/1c2LpzrL/1/)

推荐答案

您可以将<p>标记内的HTML视为字符串,然后在</label>和第一个substring >:

You can just treat the HTML inside of the <p> tag as a string and then get the substring between the </label> and the first <br>:

var totalText = $("p").html();
//determine start-pos and end-pos of desired substring, and then get it
var startPos = totalText.indexOf("</label>") + "</label>".length;
var endPos = totalText.indexOf("<br");
var targetText = totalText.substring(startPos,endPos).trim();

(小提琴: http://jsfiddle.net/3uw8ux9t/3/ )

(fiddle: http://jsfiddle.net/3uw8ux9t/3/)

  1. startPos查找第一个"</label>"的位置,然后在其中添加"</label>"的长度.
  2. endPos查找第一个"<br"的位置(我省略了结尾的>,因为正式拼写为<br />,我的方式允许两种拼写方式.)
  3. targetText最终将子字符串从startPos带到endPos.
    (.trim()从新字符串的开头和结尾删除所有空格)

  1. startPos finds the position of the first "</label>" and then adds the length of "</label>" to that.
  2. endPos finds the position of the first "<br" (I left the closing > out because officially it's spelled <br />, my way allows for both ways of spelling).
  3. targetText finally takes the substring from the startPos to the endPos.
    (.trim() removes any empty spaces from the start and end of your new string)

  • console.log(targetText)给出:

    捕获我!


  • 更新:

    发表评论后,我重新编写了脚本以适应您的指定需求:


    UPDATE:

    After your comment, I rewrote my script to accommodate for your specified needs:

    $(document).ready(function(){
      function getUnenclosedText(selector,pointer,tag) {
        var str = $(selector).html();
        //determine start-pos and end-pos
        var startPos = str.indexOf(pointer+"</"+tag+">") + (pointer+"</"+tag+">").length;
        var endPos = str.indexOf("<"+tag,startPos);
        //if there are line-breaks, reset end-pos
        if (str.indexOf("<br",startPos)<endPos || endPos==-1) {
          endPos = str.indexOf("<br",startPos);
        }
        //return substring
        if (endPos==-1) {return str.substring(startPos).trim();} //if it was the last text in the container
        else {return str.substring(startPos,endPos).trim();}
      }
      
      console.log(getUnenclosedText("p","item 1","label")); //(selector,pointer,pointerTag)
      alert('Item 1: '+getUnenclosedText("p","item 1","label") +'\n'+ 'Item 3: '+getUnenclosedText("p","item 3","label"));
    });

    p {
      font-family:arial;
    }
    
    label {
      display:inline-block;    
      width:25%;
      font-weight:bold;
    }

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <p>
      <label>item 1</label> Capture me!
      <br /><br />
      <label>item 2</label> Don't capture me
      <label>item 3</label> capture me as well
      <br /><br />
      <label>item 4</label> Don't capture me either
    </p>

    (小提琴: http://jsfiddle.net/3uw8ux9t/9/ )

    (fiddle: http://jsfiddle.net/3uw8ux9t/9/)

    我尝试使用所有参数的变量使它尽可能地可扩展,以使脚本不再局限于<p><label>.

    I tried to make it as scalable as possible, using variables for all the parameters, so that the script is not limited to <p> and <label> anymore.

    • 现在,每次要提取一段文本时,您都必须调用函数getUnenclosedText(selector,pointer,tag).这三个参数使该函数具有可伸缩性,因此您可以在各种元素上使用它,而不仅仅是<p>中的<label>:
      • "selector"指定要在其上执行功能的容器元素.因此,例如,如果您有多个具有不同ID的<p>标签,则可以使用其jQuery选择器(例如"p#someid")访问特定的<p>标签.
      • "pointer"指定要在哪一段文本(例如"item 1""item 2")上提取未封闭的文本.
      • "tag"指定包围指针的标记类型(例如"label""span").
      • You now have to call the function getUnenclosedText(selector,pointer,tag), every time you want to extract a piece of text. The three parameters make the function scalable, so you can use it on various elements, not just <label> in <p>:
        • "selector" specifies which container element(s) you want to perform the function on. So if you have multiple <p>tags with different ID's for example, you can access a specific <p> tag, using its jQuery selector (e.g. "p#someid").
        • "pointer" specifies after which piece of text (e.g. "item 1", "item 2") you want to extract the unenclosed text.
        • "tag" specifies the tag-type that encloses the pointer (e.g. "label", "span").

        如果您有任何问题,只需在评论中提问,我会回答他们,或在需要时更新此答案,但是我认为您可以在Internet上找到大部分需求.
        阅读 ,了解如何使用indexOf(),并且会理解代码中最困难的部分.

        If you have any questions, just ask them in the comments and I'll answer them or update this answer if need be, but I think you can find most of what you need on the internet.
        Read this about how to use indexOf(), and you'll understand the most difficult parts of the code.

        这篇关于如何在两个标签之间捕获字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆