I need to find and replace variables from a JavaScript code.
Lets say I need to search "length" in given code, I want to exclude "x.length" or "linelength"
Sample input - to make it easier to debug
var sampleStringWhichWorks = 'function checkLength(l, ls){\n' +
'var line, lines, len, length01, linelength11;\n' +
'line = l;\n' +
'lines = ls;\n' +
'len = line.length12;\n' +
'length02 = lines.length13;\n' +
'if(len==length03){\n' +
'len--;\n' +
'length04= length05 + 1;\n' +
'}\n' +
'linelength14 = len + length06;\n' +
'return linelength15;\n' +
'}\n';
This /([^a-z.])length[\d]{2}([^a-z])/mig expression solves the problem, but for lines like "length04=length05 + 1" it only captures the first length and ignores second.
It does work for "length04 = length05 + 1" and captures both instances.
I have added [\d]{2} just for better understanding, expected outcome here is to capture all the 'length' ending with 0 and ignore ending with 1.
I tried other options like specifying like [^a-z]{0,1}, but not solving the problem.
Check the jsFiddle here.
Actual input and regex (/([^a-z.])length([^a-z])/mig)
function checkLength(l, ls){
var line, lines, len, length, lineLength;
line = l;
lines = ls;
len = line.length;
length = lines.length;
if(len == length){
len--;
length=length+1;
}
lineLength = len + length;
return lineLength;
}
Expected outcome from this
- var line, lines, len, length, lineLength;
- length = lines.length;
- if(len == length){
- length = length + 1;
- lineLength = len + length;