Allen Marshall
Allen Marshall

Reputation: 391

Regex that matches all spaces except?

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

Upvotes: 2

Views: 96

Answers (1)

DannyMeister
DannyMeister

Reputation: 1303

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);

Upvotes: 2

Related Questions