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");
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");
Share
Improve this question
edited Jul 10, 2013 at 18:55
Dirk
asked Jul 10, 2013 at 18:49
DirkDirk
2,1443 gold badges26 silver badges29 bronze badges
3
- Is there anything you have done to try to solve this problem? We will be more willing to answer your question if you tell us what you have tried so far. (Helpful links for asking better questions: How to Ask, help center) – tckmn Commented Jul 10, 2013 at 18:52
-
I'd use
let res = input.replace(/\s+(?=[^)(]*\))/g, "");
on shorter strings and the callbacklet res = str.replace(/\([^)(]*\)/g, m => m.replace(/\s+/g, ""));
for large strings or with a lot of whitespaces inside. – bobble bubble Commented Nov 25, 2022 at 13:47 - If the parentheses are nested, it could be done by parsing (JS demo). – bobble bubble Commented Nov 25, 2022 at 13:51
2 Answers
Reset to default 6You 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');
});