简体   繁体   中英

Replace the text between two strings using JS RegEx

I have one string and I want to update the value between two comments in that string.

I'm not sure how I can do that using RegEx

var string = "/* ANIMATION START */ new string should be added here /* ANIMATION END */";

I know what I should use .replace() with RegEx , but I don't know to create the expression.

This is the Regex you will need to use:

\/\*[\w\s]+\*\/([\w\s]+)\/\*[\w\s]+\*\/

Demo:

This is a sample code you need to use to replace the text and get the desired output:

 var string = "/* ANIMATION START */ new string should be added here /* ANIMATION END */"; var regex = /(\\/\\*[\\w\\s]+\\*\\/)([\\w\\s]+)(\\/\\*[\\w\\s]+\\*\\/)/ig; string = string.replace(regex, "$1 ###ADDED TEXT### $3"); console.log(string); 

We just need to use two other matching groups respectively for the ANIMATION START and ANIMATION END parts, so we can reuse them in the replacement string.

There are 3 parts:

"(\\[\\s\\S]|[^"])*" for matching double quoted strings.

'(\\[\\s\\S]|[^'])*' for matching single quoted strings.

(//. |/*[\\s\\S] ?*/) for matching both single line and multiline comments.

The replace function check if the matched string is a comment. If it's not, don't replace. If it is, replace " and '.

function t_replace(data){
    var re = /"(\\[\s\S]|[^"])*"|'(\\[\s\S]|[^'])*'|(\/\/.*|\/\*[\s\S]*?\*\/)/g;
    return data.replace(re, function(all, strDouble, strSingle, comment) {
        if (comment) {
            return all.replace(/"/g, '"').replace(/'/g, ''');
        }
        return all;
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM