Reputation: 2144
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");
Upvotes: 3
Views: 4144
Reputation: 71598
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
Upvotes: 6
Reputation: 227310
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');
});
Upvotes: 4