简体   繁体   中英

Replace all braced strings in javascript

i want to make this:

i went to the [open shops], but the [open shops] were closed

look like this:

i went to the markets, but the markets were closed

with javascript replace

im not very good with regex and the square brackets need delimited im sure

Try this:

"i went to the [open shops], but the [open shops] were closed".replace(/\[open shops\]/g, 'markets');

The tricky part is the the need to escape the brackets and add the global match to replace each matching instance. For more info: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace

All you need to do is put \\ before [ and ] to treat it as a regular character. This way your regex would become \\[openshops\\] .

If you have multiple things that need to be replaced (eg. [shops] and [state] ) you can do the following which dynamically creates the regex. This way you don't have to hard code it for each thing.

var str = "I went to the [shops], but the [shops] were [state]. I hate it when the [shops] are [state].";
    var things = {
        shops: "markets",
        state: "closed"
    };
    for (thing in things) {
        var re = new RegExp("\\["+thing+"\\]", "g");
        str = str.replace(re, things[thing]);
    }
console.log(str);

Note that you need to use two backslashes instead of just one when doing it this way.

If you don't want to use regex. You could use something like.

    var a = "i went to the [open shops], but the [open shops] were closed";
    var replacement = "KAPOW!";

    while(a.contains("[") && a.contains("]"))
    {
        var left = a.indexOf("[");
        var right = a.indexOf("]");

        a = a.substring(0,left) + replacement + a.substring(right+ 1);
    }

    console.log(a);

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