Skip to content

Cut and paste part of the string

I am using my own tags. They start with [ and end with ].

I would like to sort the tags. So instead of


it should be


This is what I have tried so far:

const tag = 'DYNAMIC'
const str = '[TITLE|prefix=test][DYNAMIC|limit=777|random=1|reverse=0][STORENAME|prefix=SHOP]';
const regex = new RegExp(`\[${tag}[^\[]+`, 'g');
console.log(str.replace(regex, '')); 

So the tag [DYNAMIC] has been removed, which is good but it should be also placed at the beginning of the string. How can I do this?


Trivial if you want alphabetical sort

let  str =  `[TITLE|prefix=test][DYNAMIC|limit=777|random=1|reverse=0][STORENAME|prefix=SHOP]`
str = str.split("[").sort().join("[")

If you want a fixed order

const sortArr = ["DYNAMIC","TITLE","STORENAME"];

let  str =  `[TITLE|prefix=test][DYNAMIC|limit=777|random=1|reverse=0][STORENAME|prefix=SHOP]`
str = str.split("[")
  .sort((a, b) => sortArr.indexOf(a.split("|")[0]) - sortArr.indexOf(b.split("|")[0]))