3

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");
Dirk
  • 2,094
  • 3
  • 25
  • 28
  • 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: [ask], [help]) – tckmn Jul 10 '13 at 18:52
  • I'd use [`let res = input.replace(/\s+(?=[^)(]*\))/g, "");`](https://tio.run/##HcvLCoMwEEbhvU/x42qmF90WgvRBtMVpHKQlNDIJef00dHcW3/lIkeTtfeRrudUaNCNlw4RVQC94bIx/oTU2KK@uK2IwTU01O5geQbzSuKQz3af5yfQ4LczjfkHfs@t8/KYYdAhxp7axq/UH) on shorter strings and the callback `let res = str.replace(/\([^)(]*\)/g, m => m.replace(/\s+/g, ""));` for large strings or with a lot of whitespaces inside. – bobble bubble Nov 25 '22 at 13:47
  • If the parentheses are *nested*, it could be done [by parsing (JS demo)](https://tio.run/##XVFBasMwELzrFZOTJYzjtL0UhB/QW6HXHmKUdesiJOOVc2nydndlO6HtwiJmNaOZRV/tuWU39kOqzs/z7CmhD8OU0OAYp8T9iaD9QfrBYD2lHyGl/ZMx5nZj8JuOm0SAcKTkFkerVF2Dk/iBh9aRmC2aQJzohKEdKaRPYmLVTcGlPoaV/pbZ/BJetUCjvpVYSNaRWJIWhd1wHCjI4JBxF0doFwMnOMQOixDIUqm@0w6NaHVh1gkWdVnaFZJniddho5m/tKraaPfXdov35YJd/c71PslG2pm7KCctG7gsu6qM0zSGPLbqqtS6yL9Vl58wVuUloqe9jx9aiMbO8w8). – bobble bubble Nov 25 '22 at 13:51

2 Answers2

6

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
Jerry
  • 70,495
  • 13
  • 100
  • 144
3

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');
});
gen_Eric
  • 223,194
  • 41
  • 299
  • 337