gpt4 book ai didi

JavaScript 围绕大括号拆分

转载 作者:数据小太阳 更新时间:2023-10-29 05:15:17 24 4
gpt4 key购买 nike

我在字符串变量中有一个字符串格式:

"{0} Hello World {1}"

我需要把它分成这样的东西:

"{0}","Hello World","{1}"

根据我的努力,我能得到的最好结果是:

"","0"," Hello World ","1",""

我试过从 Regex Split Around Curly Braces 转换示例但它没有用,那里的拆分要么删除所有内容,要么保留空格并删除 {}

那么,我的问题与另一篇文章中的问题相同,如何保留大括号 {} 并删除它们前后的空格而不是单词之间的空格?

最佳答案

您可以使用 Split with a regex having capturing group(s) :

If separator is a regular expression that contains capturing parentheses, then each time separator is matched, the results (including any undefined results) of the capturing parentheses are spliced into the output array.

var re = /\s*(\{[0-9]+\})\s*/g;
var splt = "{0} Hello World {1}".split(re).filter(Boolean);
alert(splt);

正则解释:

  • \s* - 任意数量的空格
  • (\{[0-9]+\}) - 匹配的捕获组:
    • \{ - 文字 {
    • [0-9]+ - 1 个或多个数字
    • \} - 文字 }
  • \s* - 任意数量的空格

filter可以帮助摆脱数组中的空元素。

filter() calls a provided callback function once for each element in an array, and constructs a new array of all the values for which callback returns a true value or a value that coerces to true. callback is invoked only for indexes of the array which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values.

Array elements which do not pass the callback test are simply skipped, and are not included in the new array.

关于JavaScript 围绕大括号拆分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30576177/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com