Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript regex replace spaces between brackets

How can I use JS regex to replace all occurences of a space with the word SPACE, if between brackets? So, what I want is this:

myString = "a scentence (another scentence between brackets)"
myReplacedString = myString.replace(/*some regex*/)
//myReplacedString is now "a scentence (anotherSPACEscentenceSPACEbetweenSPACEbrackets)"

EDIT: what I've tried is this (I'm quite new to regular expressions)

myReplacedString = myString.replace(/\(\s\)/, "SPACE");
like image 280
Dirk Avatar asked Jan 25 '26 04:01

Dirk


2 Answers

You could perhaps use the regex:

/\s(?![^)]*\()/g

This will match any space without an opening bracket ahead of it, with no closing bracket in between the space and the opening bracket.

Here's a demo.

EDIT: I hadn't considered cases where the sentences don't end with brackets. The regexp of @thg435 covers it, however:

/\s(?![^)]*(\(|$))/g
like image 50
Jerry Avatar answered Jan 26 '26 16:01

Jerry


I'm not sure about one regex, but you can use two. One to get the string inside the (), then another to replace ' ' with 'SPACE'.

myReplacedString = myString.replace(/(\(.*?\))/g, function(match){
    return match.replace(/ /g, 'SPACE');
});
like image 28
Rocket Hazmat Avatar answered Jan 26 '26 18:01

Rocket Hazmat