1

given the following text, I'd like to replace the spaces within the parentheses with '-'

str = 'these are the (1st 2nd and last) places'

// expected result
// 'these are the (1st-2nd-and-last) places'

In other words, replace all the spaces that are preceded by a '(' and (something) and followed by (something) and a ')'.

I started with

/(?<=\(\w+)\s/g

but (regex101 tells me that) "a quantifier inside a lookbehind makes it s non-fixed width" (referring to the \w+). What is a better approach to solving this?

1 Answer 1

1

You are using the wrong regex flavor. In JavaScript, you can use

.replace(/(?<=\([^()]*)\s+(?=[^()]*\))/g, '-')

See the regex demo. The pattern matches and replaces with a - the following pattern:

  • (?<=\([^()]*) - a location that is immediately preceded with ( and any zero or more chars other than ( and )
  • \s+ - one or more whitespaces
  • (?=[^()]*\)) - that must be followed with zero or more chars other than ( and ) and then a ) char.

If the JavaScript environment you are using is old and does not support infinite width lookbehind, you can use

.replace(/\([^()]+\)/g, function(x) { return x.replace(/\s+/g, '-') })

That is, match any strings between round parentheses and replaces all chunks of one or more whitespace with - inside those matches.

See

console.log(
  'these are the (1st 2nd and last) places'.replace(/(?<=\([^()]*)\s+(?=[^()]*\))/g, '-')
)

and

console.log(
  'these are the (1st 2nd and last) places'.replace(/\([^()]+\)/g, function(x) { 
    return x.replace(/\s+/g, '-') 
  }))

Sign up to request clarification or add additional context in comments.

1 Comment

thanks. you are correct, the running environment matters. Your regex demo doesn't work in Safari 14.1.1 but works correctly in Visual Studio Code. Thanks also for the hint about "zero or more chars other than ( and )"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.