0

Would it be possible to change

(Test 1 / Test 2) [Test 3] Отдел / Here is title - subtitle (by Author) - 1234 (5678-9999), descriptions (best), more descriptions

to

Here is title - subtitle (1234) (descriptions)

using JavaScript with Regex?

Currently, I have to combine multiple replace functions, like below

let text = '(Test 1 / Test 2) [Test 3] Отдел / Here is title - subtitle (by Author) - 1234 (1234-4567), descriptions (best), more descriptions';

text = text
  .replace(/ *\([^) ]*\) */g, "")
  .replace(/ \([\s\S]*?\)/g, '')
  .replace(/[0-9`~!@#$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/]/gi, '');

console.log(text);

But it doesn't working as expected. Anyone have any ideas?

mplungjan
  • 169,008
  • 28
  • 173
  • 236
Hung PD
  • 405
  • 2
  • 15
  • 33

1 Answers1

1

Entering this as an answer to "prove" that it works ;)

But, as I said in comment, it's not pretty. There must be a better way.

Anyway, what it does is to consume (match) everything inside the first parenthesis pair with \([^)]*\). After that it matches everything up to / (inclusive) with [^/]*?\/\s* (made the first part there non greedy which it wasn't originally). Then it captures the title, up to (, with ([^(]*?)\s*\(. After that it's time to match up to 1234. Done with [^)]*\)\s*-\s*.

Time to capture 1234 with (\d+) (I'm assuming it's always a number, otherwise you need to replace it with something lik ([^)]*).

Math up to the description with \s*\([^)]*\),\s* and capture it with (.*?)\s\( (the \s\( is to not get it in the capture group).

Finally match the rest with .*$ (not really necessary, but... :)

Replace all this with $1 ($2) ($3) to get parentheses in the right places. Voila :D

let text = '(Test 1 / Test 2) [Test 3] Отдел / Here is title - subtitle (by Author) - 1234 (1234-4567), descriptions (best), more descriptions';

console.log(text.replace(/^\([^)]*\)[^/]*?\/\s*([^(]*?)\s*\([^)]*\)\s*-\s*(\d+)\s*\([^)]*\),\s*(.*?)\s\(.*$/gm, '$1 ($2) ($3)'));
SamWhan
  • 8,296
  • 1
  • 18
  • 45