Sort each section separately using bookmarklet

Viewed 78

I use wikipedia syntax in text area. My text looks like this...

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

I use the bookmarklet that I found here...

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

When I sort, I get this. How do I sort each section separately?

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

Expected:

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

This awk command works:

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

But awk can not be used in browser. Is it possible to include transform in JS bookmarklet?

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

1 Answers

Try something like this:

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>

Bookmarklet:

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>

Related