【问题标题】:How can I reorder strings of text using regex and javascript?如何使用 regex 和 javascript 重新排序文本字符串?
【发布时间】:2018-09-20 09:54:16
【问题描述】:

例如,我在 textarea 中有这个:

 <textarea>
   <div class="sections">
     <div class="item" id="apple">
        Apple
     </div>
     <div class="item" id="blueberry">
        Blueberry
     </div>
     <div class="item" id="orange">
        Orange
     </div>
   </div>
 </textarea>

使用正则表达式,我想像这样重新排序字符串:

  <textarea>
    <div class="sections">
      <div class="item" id="orange">
         Orange
      </div>
      <div class="item" id="blueberry">
         Blueberry
      </div>
      <div class="item" id="apple">
         Apple
      </div>
    </div>
  </textarea>

我想过做这样的事情,但做的不对:

var string = $("textarea").val() // note: I want to keep this as a string
new_content = string.replace(/<div class="sections">(.*)<\/div>/, '<div class="sections"></div>') // remove inner content
new_content = new_content + string.match(/<div.*id="orange">(.*)<\/div>/)[0]
new_content = new_content + string.match(/<div.*id="blueberry">(.*)<\/div>/)[0] 
new_content = new_content + string.match(/<div.*id="apple">(.*)<\/div>/)[0] 

有什么想法吗?

【问题讨论】:

  • HTML 不是正则语言,你不能用正则表达式真正解析它
  • 这是您的真实输入吗?我的意思是 div 内容等于它们的 id?
  • div 内容是一些示例文本 :)

标签: javascript jquery html regex


【解决方案1】:

这是您正在寻找的正确正则表达式。您假设 .* 匹配换行符,这不是 javascript 的默认值。

您可以在此处阅读更多信息: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp

$(() => {
  var string = $("textarea").val() // note: I want to keep this as a string
  
  new_content = string.match(/\s*<div.*?class="sections">/g)[0];
  new_content += string.match(/\s*<div.*?id="orange">(.|\s)*?<\/div>/g)[0]
  new_content += string.match(/\s*<div.*?id="blueberry">(.|\s)*?<\/div>/g)[0] 
  new_content += string.match(/\s*<div.*?id="apple">(.|\s)*?<\/div>/g)[0]
  new_content += string.match(/.*>(\s*<\/div>)/s)[1];
  
  $('textarea').val(new_content);

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

 <textarea>
   <div class="sections">
     <div class="item" id="apple">
        Apple
     </div>
     <div class="item" id="blueberry">
        Blueberry
     </div>
     <div class="item" id="orange">
        Orange
     </div>
   </div>
 </textarea>

【讨论】:

  • 这是优秀的莱纳多!太感谢了!!我正要关闭这个话题,因为我看到了反对票并且认为这不能用正则表达式解决,但我很高兴在我这样做之前看到了你的解决方案。再次感谢莱纳多!! :)
猜你喜欢
  • 2020-09-30
  • 1970-01-01
  • 1970-01-01
  • 2017-03-31
  • 2022-12-14
  • 1970-01-01
  • 2020-04-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多