I am trying to find for loop pattern in javascript code, and replace syntax (from : to in), using below regex way,
var str="for(var x in []) for(var y in [])";
str.replace( new RegExp( '(for\\s*\\(.+\\s+):(\\s+.+\\))', 'ig' ), "\$1in\$2" )
i.e.
for(var x : list)
{
// something
}
with
for(var x in list)
{
// something
}
However I am facing issues when there are multiple for loops in same line.
for(var x : list) { for(var y : list) {
// something
}
}
which is valid syntax, however due to Greedy regex approach it converts as below:
for(var x : list) { for(var y in list) {
// something
}
}
I tried to explore lazy regex syntax but couldn't make it work. How can I achieve this ?
str.split(':').join(' in ')? Or you only want to do it as part of for loops?