简体   繁体   中英

Regexp, replace certain combinations

Got this string: "'ab',('AA', 'BB'), r('rr')"

I want the output to be "'ab',['AA', 'BB'], r('rr')"

Tried this

var replace = function(str){
    return str.replace(/\)/g, ']')
  .replace(/\(/g, '[')
}

It replaces all paranthes but how do I combine the regexp so it only replaces ,( with [ ?

https://jsfiddle.net/tyapco67/

只需在括号前添加逗号:

return str.replace(/(,\s*)\((.*?)\)/g, '$1[$2]');

没有RegEx

"'ab',('AA', 'BB'), r('rr')".split(",(").join(",[").split("),").join("],")

I like to use the [^]* inverse selector personally. Thus it doesn't require the comma.

var replace = function(str){
    return str.replace(/\(([^)]*)\)/g, "[$1]");
}

The currently accepted answer would produce 'ab',['AA', 'BB'], r('rr') .

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