微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用书签分别对每个部分进行排序

如何解决使用书签分别对每个部分进行排序

我在文本区域使用维基百科语法。我的文字看起来像这样...

=main-heading=
test
again
practice
==sub-heading==
america
usa
india

我使用在这里找到的书签...

https://gist.github.com/aquilax/ac94ea6003f2ddb1e1fd6195c00ac3d9

当我排序时,我得到了这个。如何分别对每个部分进行排序?

==sub-heading==
=main-heading=
again
america
india
practice
test
usa

预期:

=main-heading=
again
practice
test
==sub-heading==
america
india
usa

这个 awk 命令有效:

awk '/=/ {c++} {print c+1,$0}' t1.txt |排序 -n | cut -d' ' -f2- | sed '/^$/d'

但是awk不能在浏览器中使用。是否可以在 JS 书签中包含转换?

https://en.wikipedia.org/wiki/Schwartzian_transform

解决方法

尝试这样的事情:

function sortSections() {
  const textarea = document.querySelector('textarea');

  textarea.value = textarea.value
    .trim()
    .split(/\n(?==.+=$)/m)
    .map(section => {
      const [heading,body] = section.split(/(?<==)\n/);
      return `${heading}\n${[...new Set(body.split('\n'))].sort().join('\n')}`;
    })
    .join('\n');
}
<textarea cos="40" rows="10">=main-heading=
test
again
practice
==sub-heading==
india
america
usa
india</textarea>

<button onclick="sortSections();">Sort</button>

书签:

javascript: {
  const textarea = document.querySelector('textarea');

  void (textarea.value = textarea.value
    .trim()
    .split(/\n(?==.+=$)/m)
    .map(section => {
      const [heading,body] = section.split(/(?<==)\n/);
      return `${heading}\n${[...new Set(body.split('\n'))].sort().join('\n')}`;
    })
    .join('\n'));
}

<a href="javascript: {  const textarea = document.querySelector('textarea');  void (textarea.value = textarea.value    .trim()    .split(/\n(?==.+=$)/m)    .map(section => {      const [heading,body] = section.split(/(?<==)\n/);      return `${heading}\n${[...new Set(body.split('\n'))].sort().join('\n')}`;    })    .join('\n'));}">Bookmarklet</a>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。