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");
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
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');
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With