【问题标题】:jQuery extract text within double quotesjQuery提取双引号内的文本
【发布时间】:2015-03-05 08:24:29
【问题描述】:

我有带有传统双引号的大型 HTML 文件,例如 并以 结尾我如何在这些双引号中提取纯文本

很遗憾quote open和quote close不在同一个p标签中。

我的 HTML 是这样的

<p>“And, as best friends, you would have shopped lots of times before, wouldn’t you? You’re best friends?</p>
<p>---Yes but not before that time, not before she gave birth to Shelby we weren’t shopping as much.</p>
<p>Not as much?</p>
<p>---No.”</p>

最后我想要实现的是我应该用双引号修剪所有标签,以便双引号内的全文将在一个p标签中。

谢谢

【问题讨论】:

    标签: jquery regex


    【解决方案1】:

    这应该适合你

    var str = '<p>“And, as best friends, you would have shopped lots of times before, wouldn’t you? You’re best friends?</p><p>---Yes but not before that time, not before she gave birth to Shelby we weren’t shopping as much.</p><p>Not as much?</p><p>---No.”</p>';
    
    // get text within quotes
    var String=str.substring(str.lastIndexOf('“')+1,str.lastIndexOf('”'));
    
    // now to strip tags
    String = String.replace(/<p>/g, '');
    String = String.replace(/<\/p>/g, '');
    console.log(String);
    

    【讨论】:

    • 其实问题不是去掉引号而是去掉p标签
    • 为您更新答案
    【解决方案2】:

    试试这个脚本:

    var text = "";
    $("p").each(function(){
        text += $(this).text().trim();
    }
    text = text.substring(1, text.length-1); //Removes last and first character
    console.log(text);
    

    这里是fiddle

    【讨论】:

      【解决方案3】:

      如果你的 html 文件中有一堆这样的小对话框,那么下面的想法可能会奏效。首先从 p-tags 中提取文本。然后通过启动和关闭 qoutes 对它们进行分组。例如使用Array.prototype.reduceDemo.

      $('p') //find tags
      .toArray() //make array
      .map(function(p){
          return $(p).text();
      }) //extract text
      .reduce((function(){ 
          var collecting = 0, buffer = [];
          function begin(txt) { //start grouping
              if(collecting) throw new Error('Incorrect opening quote');
              collecting = 1;
              buffer = [txt];
          }
          function end(text) { //end grouping
              if(!collecting) throw new Error('Incorrect closing quote');
              buffer.push(text);
              var txt = buffer.join('\n');
              collecting = 0;
              buffer = [];
              return txt;
          }
          return function(arr, text) { //reducer
              var start = text.indexOf('“') >= 0,
                  stop = text.indexOf('”') >= 0;
              if(start) {            
                  begin(text);            
              }
              else if(stop) {
                  arr.push(end(text));    
              }
              else {
                  buffer.push(text);    
              }
      
              return arr;
          };
      }()), []); //group by quotes
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-11-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多