简体   繁体   中英

JavaScript regexp replace spaces that match certain condition

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?

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, '-') }))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM