I've a less file with content like this:
@background: #345602;
@imgBack: #000;
I can read the whole text file into a variable, and latter save the content of the variable modifying the file:
var lessStr = grunt.file.read('./myLessFile.less');
Now I want to change the variable, say, @imgBack to #ff0000. So that, the modified file would look like:
@background: #345602;
@imgBack: #ff0000;
I there any way to do this by regular expression match and replace? Please help.
EDIT
I've code like:
var str = '@black: #000;\n@grayDarker: #222;\n@grayDark: #333;\n@gray: #555;\n@grayLight: #999;';
var varName = '@black';
var replace = '#ab4564';
var regex = '(' + varName + ':\\s*)(?:#[a-z0-9]+)(.*)$';
var re = new RegExp(regex, 'm');
var replaceStr = '$1' + replace;
str.replace(re, replaceStr);
console.log(str);
But it's not working. Have I mistaken something.
I think you mean this,
> var str = "@background: #345602;\n@imgBack: #000;";
> str.replace(/^(@imgBack:\s*#).*$/gm, "$1ff0000;");
'@background: #345602;\n@imgBack: #ff0000;'
Update:
> var str = '@black: #000;\n@grayDarker: #222;\n@grayDark: #333;\n@gray: #555;\n@grayLight: #999;';
undefined
> var varName = '@black';
> var regex = '(' + varName + ':\\s*)(?:#[a-z0-9]+)(.*)$';
undefined
> var re = new RegExp(regex, 'm');
> var replace = '#ab4564';
undefined
> var replaceStr = "$1" + replace;
undefined
> str.replace(re, replaceStr);
'@black: #ab4564\n@grayDarker: #222;\n@grayDark: #333;\n@gray: #555;\n@grayLight: #999;'
(@imgBack:\s*#)(?:\d+)(.*)$
You can use this.Replacement string will be.
$1#ff0000$2.
See demo.