如果特定单词在javascript中匹配,则替换行

时间:2012-07-30 09:33:45

标签: javascript regex string

如果行中的特定单词匹配,那么我想读取整行。 我怎么能这样做。

喜欢如果

var str = "this is test sample msg \n this is second line \n  ";
包含'sample'字样的

行将返回。

我该如何在javascript中执行此操作?

3 个答案:

答案 0 :(得分:3)

var str = "this is test sample msg \n this is second line \n third samples";
str.split("\n").filter(function(str) {
    return ~str.indexOf("sample")
});
//["this is test sample msg ", " third samples"]

答案 1 :(得分:0)

试试这个

var line = "sample text", var str = "sample";
if(line.indexOf(sample) > 0){
//do something
}else{
//do something else
}

答案 2 :(得分:0)

function returnLine(lines, str)
{
    var i, lines = lines.split("\n");

    for(i=0; i<lines.length; i++)
    {
        if(lines[i].indexOf(str) !== -1)
        {
            return lines[i];
        }
    }

    return '';
}

使用:

returnLine("this is test sample msg \n this is second line \n ", "sample");