user2894296
user2894296

Reputation: 630

Regex to add a new line break after each bracket

I have tried using replace with regex (/\([(]\)/g,'\1\n') but its not helping. Any help?

Upvotes: 2

Views: 5145

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627110

Regardless what the language is, a round bracket matching pattern is either \( or [(]. If you need to use a whole match value in the replacement, there are $& or $0 backreferences.

Thus, search for /[(]/g (you may add more chars into the character class, like [()\][]...) and replace with "$&\n" (or "$0\n").

See the regex demo.

A JS demo:

var regex = /[(]/g;
var str = "before(after and before 1(after1";
var subst = "$&\n";
var result = str.replace(regex, subst);
console.log(result);

Upvotes: 3

Related Questions