2

Regex that matches all spaces but:

  1. \sand\s
  2. \sor\s
  3. \sbut\s
  4. ,\s


Input

font weight, width and height, background, or background color, but transform style


input.replace(regex,"-")


Matches

fontweight, width and height, background, or backgroundcolor, but transformstyle


Replace

font-weight, width and height, background, or background-color, but transform-style


Output

font-weight, width and height, background, or background-color, but transform-style

Allen Marshall
  • 381
  • 2
  • 10
  • Updated the question – Allen Marshall Sep 28 '17 at 03:41
  • Unfortunately, Javascript doesn't support negative lookbehind, so this could be quite difficult. One quick thing to note: `\s` is not regex for "space". It's a character set that includes all whitespace characters (space, tab, newline, carriage return, form feed, and vertical tab). You could get unexpected behavior if you use `\s` when you only want to match ` `. – CAustin Sep 28 '17 at 03:41
  • `\t` `\n` `\r` have already been removed… so the only thing left are spaces. – Allen Marshall Sep 28 '17 at 03:43
  • Sure, but you can still just use a literal space. That's what you're trying to match, right? At the very least you'll save space because you're using one character instead of two. – CAustin Sep 28 '17 at 03:44
  • 1
    I just used `\s` to show space in question… otherwise it won't show up. – Allen Marshall Sep 28 '17 at 03:47
  • `@CAustin`s comment about the `\s` is irrelevant if your outputting to HTML, since one or more white spaces and/or line breaks is just a single space in HTML. – StackSlave Sep 28 '17 at 03:57

1 Answers1

2

Since JavaScript doesn't support look behinds, you won't find a regex which will be able to do it as simply as the replace as you have there. If you are willing to extend the replace logic a bit, you can use an answer such as the following (adapted from answer here: Regex negative lookbehind not valid in JavaScript)

var input = " font weight, bland food, width and height, background, or background color, but transform style, and background repeat"
var regex = /\b(\s?and|\s?but|\s?or|,)?\s/g
var output = input.replace(regex, function($0, $1) {
   return ($1 ? $0 : "-")
});
console.log(output);
DannyMeister
  • 1,281
  • 1
  • 12
  • 21