【问题标题】:How can I select a string within a string and save it into a variable with jQuery?如何在字符串中选择一个字符串并使用 jQuery 将其保存到变量中?
【发布时间】:2011-03-16 21:16:36
【问题描述】:

我有一个动态输入的字符串:

<span class="note_message">The order was manually edited:<br/>The list of edits goes here, and this maybe somewhat long sometimes</span>

这是一个可以输入到 span 中的字符串示例。它总是以“订单被手动编辑:”开头,所以我想使用 jQuery 来查看字符串是否在开头包含这些单词,如果是,则在“订单被手动编辑:”之后选择字符串的其余部分: " 并将其保存到单独的变量中。

我该怎么做呢?

【问题讨论】:

    标签: jquery string contains


    【解决方案1】:

    试试这个:

    var Str=$(".note_message").filter(function(){
      return $(this).text().match(/^The order was manually edited\:/);
    }).text().replace(/The order was manually edited\:/,'');
    

    这里是the code in action

    【讨论】:

      【解决方案2】:

      您可以使用text() 检索元素的文本——这将递归地收集元素中的所有文本:

      var text = $('.note_message').text();
      

      然后,你可以删除你不想要的位:

      text = text.replace(/^The order was manually edited:/, '');
      text; // => "The list of edits goes here, and this ..."
      

      【讨论】:

        【解决方案3】:

        我相信 jQuery 能为你提供的唯一帮助就是选择跨度。

        然后是它的值。

        jQuery('.note_message').val();

        您可以使用简单的 javascript 字符串函数(如 indexOf)来检查值是否包含匹配的文本。

        var x = jQuery('.note_message').val();
        if(x.indexOf('yuor matching text')!=-1)

        执行您需要的操作

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2014-02-21
          • 1970-01-01
          • 2020-07-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-08-24
          相关资源
          最近更新 更多