Javascript regex replace spaces between brackets

How can I use the JS regular expression to replace all occurrences of space with the word SPACE, if between brackets? So I want this:

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

EDIT: what I tried this (I'm brand new to regexes)

myReplacedString = myString.replace(/\(\s\)/, "SPACE");
+1
source share
2 answers

Perhaps you can use a regex:

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

This will match any space without an open bracket in front, without a closing bracket between the space and an opening bracket.

Here is a demo .

EDIT: I have not considered cases where sentences do not end with parentheses. The @ thg435 regular expression covers it, however:

/\s(?![^)]*(\(|$))/g
+4
source

, . , (), , ' ' 'SPACE'.

myReplacedString = myString.replace(/(\(.*?\))/g, function(match){
    return match.replace(/ /g, 'SPACE');
});
+2

All Articles