Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex: How do I remove the character BEFORE the matched string?

I am intercepting messages which contain the following characters:

*_-

However, whenever any one of these characters comes through, it will always be preceded by a \. The \ is just for formatting though and I want to remove it before sending it off to my server. I know how to easily create a regex which would remove this backslash from a single letter:

'omg\_bbq\_everywhere'.replace(/\\_/g, '')

And I recognize I could just do this operation 3 times: once for each character I want to remove the preceding backslash for. But how can I create a single regex which would detect all three characters and remove the preceding backslash in all 3 cases?

like image 925
chopper draw lion4 Avatar asked Sep 25 '22 11:09

chopper draw lion4


1 Answers

You can use a character class like [*_-].

To remove only the backslash before these characters:

document.body.innerHTML =
   "omg\\-bbq\\*everywhere\\-".replace(/\\([*_-])/g, '$1');

When you place a subpattern into a capturing group ((...)), you capture that subtext into a numbered buffer, and then you can reference it with a $1 backreference (1 because there is only one (...) in the pattern.)

like image 143
Wiktor Stribiżew Avatar answered Nov 15 '22 05:11

Wiktor Stribiżew