grunt-text-replace 和正则的一些小记

2016-10-14  本文已影响0人  唐小狼

1、grunt-text-replace

使用grunt来压缩前端文件的时候,经常涉及到index文件种的内容替换,grunt-text-replace是实现这种功能的一个插件。npm网站上对grunt-text-replace的用法有多种介绍,一般有下面两种:
1、第一种

replace: {
  example: {
    src: ['text/*.txt'],             // source files array (supports minimatch) 
    dest: 'build/text/',             // destination directory or file 
    replacements: [{
      from: 'Red',                   // string replacement 
      to: 'Blue'
    }, {
      from: /(f|F)(o{2,100})/g,      // regex replacement ('Fooo' to 'Mooo') 
      to: 'M$2'
    }, {
      from: 'Foo',
      to: function (matchedWord) {   // callback replacement 
        return matchedWord + ' Bar';
      }
    }]
  }
}

2、第二种

replace: {
  another_example: {
    src: ['build/*.html'],
    overwrite: true,                 // overwrite matched source files 
    replacements: [{
      from: /[0-9]{1,2}\/[0-9]{1,2}\/[0-9]{2,4}/g,
      to: "<%= grunt.template.today('dd/mm/yyyy') %>"
    }]
  }
}

第一种有dest目标文件,一般都是将源文件进行替换后,再压缩到目标文件。
而第二种方法是重写源文件,即源文件保留,把里面的内容进行替换。以第二种方法为例进行介绍,
(1)src为要操作的源文件;
(2)overwrite为true时表示会重写源文件;
(3)from为一个正则表达式,用来匹配查找要替换的内容;
(4)to为用来替换的内容,它可以直接是一个字符串,也可以是一个function,当然function最后还是要返回一个字符串,用来替换源文件的内容。

例如下面这段代码:

numberRe: {
     src: ['../index.phtml'],
     overwrite: true,
     replacements: [{
     from: /(version:")([0-9.]+)(")[\S\s]*(isDebug: true)/g,
     to: function(matchedWord, index, fullText, regexMatches){
     var regN = /[0-9]+$/;
     var versionNum = parseInt(regexMatches[1].match(regN), 10) + 1;
     var addVer = regexMatches[1].replace(regN, versionNum);
     return matchedWord.replace(/(version:")([0-9.]+)(")[\S\s]*(isDebug: true)/, "$1"+addVer+"$3"+",\nisDebug: false");
       
       }
       }]
    }

关键字to的值就是一个function,注意这个function是可以传参的,它有四个参数,分别为:
(1)matchedWord 根据form正则表达式匹配出来的the matched world(完全匹配的内容)
(2)index 是一个下标,指向匹配内容第一次出现的地方
(3)fullText 所有的源文件内容
(4)regexMatches 是一个数组,里面是正则表达式匹配出的内容,注意这些内容是正则表达式种用 ()包含起来的大原子所匹配出来的内容。
例如官方文档种给出的例子:

// Where the original source file text is:  "Hello world" 
 
replacements: [{
  from: /wor(ld)/g,
  to: function (matchedWord, index, fullText, regexMatches) {
    // matchedWord:  "world" 
    // index:  6 
    // fullText:  "Hello world" 
    // regexMatches:  ["ld"] 
    return 'planet';   // 
  }
}]
 
// The new text will now be:  "Hello planet" 

2、正则小记

/(version:")([0-9.]+)(")[\S\s]*(isDebug: true)/g

()将正则表达式的原子分成组,变成一个个大原子。当字符串用正则表达式进行匹配时,这些原子匹配成功后都会成为匹配结果中的一个元素。
例如下面这段代码:

export function regText(){
    var str = "hello!";
    var reg = /(h)[\w]*(l)(\w)(!)/;
    var res = str.match(reg);
    console.log(res);
}

它的输出就是下面这样:

["hello!", "h", "l", "o", "!", index: 0, input: "hello!"]
0:"hello!"
1:"h"
2:"l"
3:"o"
4:"!"
index:0
input:"hello!"
length:5

具体需要如何操作,就可以根据情况去选择元素了。

上一篇 下一篇

猜你喜欢

热点阅读