JavaScript Split around curly braces

前端 未结 5 2143
再見小時候
再見小時候 2021-02-09 09:40

I have a string format inside of a string variable:

\"{0} Hello World {1}\"

I need to split it into something like this:

\"{0}\         


        
5条回答
  •  南旧
    南旧 (楼主)
    2021-02-09 10:18

    var myString = "{0} Hello World {1}"
    var splits = myString.split(/\s?{\d}\s?/);
    

    which would return ["", "Hello World", ""],

    var count = 0;
    for (var i=0; i< splits.length; i++) {
        if (splits[i] === "") {
            splits[i] = "{" + count + "}";
            count++;
        }
    }
    

    now splits would have what you need.

提交回复
热议问题