Regex Replace不服从1美元

时间:2013-07-12 09:23:26

标签: javascript regex

var input = document.getElementById('textinput').value;
var lines = input.split('\n');
var output = '';       
$.each(lines, function(key, line) {

    for(var iii=0; iii<=key; iii++) //for each line
    {
        var filenameRegex = /^\* \[\[Media:(.+?)(\|)/;
        var results = lines[iii].match(filenameRegex);
        var filename;
        console.log('lines[iii]= '+lines[iii]);
            if(results!==null && results.length!== 0)
            {
                  output += lines[iii].replace(filenameRegex,'$1'); 
            }
    }

我努力但输出总是output += lines[iii].replace(filenameRegex,'$1$2') 即使我只想要$ 1

输入示例:* [[Media:importantstuff | unimportantstuff]]

预期产出:重要资产

实际输出:importantstuffunimportantstuff]]

1 个答案:

答案 0 :(得分:1)

如果我理解正确,你正在寻找:

Demo

代码:

var filenameRegex = /^\* \[\[Media:(.+?)\|.*/;
var results = lines[iii].match(filenameRegex);
var filename;
console.log('lines[' + iii + ']= ' + lines[iii]);
console.log('key[' + iii + ']= ' + key);
if (results !== null && results.length !== 0) {
    output += lines[iii].replace(filenameRegex, '$1');
}