DennisTurn DennisTurn - 5 months ago 10
Javascript Question

Find and replace content within a string

I literally cannot find the solution for this anywhere. Is it possible to find everything from

start
and
end
, and the content inside.

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 */";


I've added the start and end as I've already extracted them, but how do I do a search for the
start
and
end
, and then once I've the start and end found how do I replace everything from start to end. So ideally once I've found the following:

This is what I am looking for, and ideally be able to replace it with a variable

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


I can replace it with a variable. I feel like since I'm searching for the start and end, this has to be some sort of regex solution, but my regex is heavily limited.

New content variable

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


Input

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

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


Expected output

/* 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 */";

Answer

Just for test case the needed replacement can be achieved by the following regex pattern and String.replace function:

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);

The output:

/* 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 */