查找并替换字符串中的内容

时间:2016-06-25 17:34:37

标签: javascript regex

我无法在任何地方找到解决方案。是否可以找到startend以及内容中的所有内容。

var start = "/* Start: User One */";
var end = "/* End: User One */";

var userCSS = "
/* Start: User One */ 
div.user_one {height: 700px;}
/* End: User One */

/* Start: Storm */ 
div.storm {height: 500px;}
/* End: Storm */";

我已经添加了开头和结尾,因为我已经提取了它们,但是我如何搜索startend,然后一次&#39 ;开始和结束发现如何从头到尾替换所有内容。理想情况下,一旦我找到了以下内容:

这就是我要找的,理想情况下可以用变量替换它

/* Start: User One */ 
div.user_one {height: 700px;}
/* End: User One */

我可以用变量替换它。我觉得既然我正在寻找开始和结束,这必须是某种正则表达式解决方案,但我的正则表达式受到严重限制。

新内容变量

/* Start: User One */ 
div.user_one {height: 500px;}
div.user_one h1 {height: 500px;}
/* End: User One */

输入

/* Start: User One */ 
div.user_one {height: 500px;}
/* End: User One */

/* Start: Storm */ 
div.storm {height: 500px;}
/* End: Storm */";

预期输出

/* Start: User One */ 
div.user_one {height: 500px;}
div.user_one h1 {height: 500px;}
/* End: User One */

/* Start: Storm */ 
div.storm {height: 500px;}
/* End: Storm */";

1 个答案:

答案 0 :(得分:2)

仅针对测试用例,可通过以下正则表达式模式和String.replace函数实现所需的替换:

var start = "/* Start: User One */",
    end = "/* End: User One */",
    userCSS = "/* Start: User One */ div.user_one {height: 700px;}/* End: User One *//* Start: Storm */ div.storm {height: 500px;}/* End: Storm */",
    newContent = "/* Start: User One */div.user_one {height: 500px;}div.user_one h1 {height: 500px;}/* End: User One */";

// you should always escape special characters in dynamic variables which are a part of a regular expression.    
var quote = function(str) {
        return str.replace(/([.?*+^$[\]/(){}|-])/g, "\\$1");
    },
    re = new RegExp(quote(start) + "[^/]+" + quote(end)),
    newCss = userCSS.replace(re, newContent);

console.log(newCss);

输出:

/* Start: User One */div.user_one {height: 500px;}div.user_one h1 {height: 500px;}/* End: User One *//* Start: Storm */ div.storm {height: 500px;}/* End: Storm */