How to replace all spaces except spaces inside "a b" in RegEx?

How to replace all white space characters with the letter "_", except for spaces between the characters "a" and "b", like this is "ab".

// this is what I have so far to save someone time (that a joke) var result:String = string.replace(/ /g, "_"); 

Oh, this is in JavaScript.

+4
source share
2 answers

Use this:

 var result:String = string.replace(/([^a]) | ([^b])/g, "$1_$2"); 

A simplified explanation of the above is that it replaces a space that either:

  • preceded by a character other than a
  • followed by a character other than b

Note. To generalize the regex to include tabs and newlines, use \s , for example:

 var result:String = string.replace(/([^a])\s|\s([^b])/g, "$1_$2"); 
+4
source

Try this regex:

 /(?!a)\s(?!b)/g 

Edit: This is not the best solution, as KendallFrey pointed out.

+2
source

All Articles