javascript - 如何删除 [ 和 ] 以及之间的任何内容 (javascript)

标签 javascript arrays string

如果内容只包含数字,如何删除'['和']'以及其间的内容?

起始字符串:

let cityInfo = "Munich (/ˈmjuːnɪk/ MEW-nik; German: München [ˈmʏnçn̩] (listen);[3] Austro-Bavarian: Minga [ˈmɪŋ(ː)ɐ]; Latin: Monachium) is the capital and most populous city of Bavaria. With a population of around 1.5 million,[4] it is the third-largest city in Germany."

“[]”之间的一些信息我需要保留。示例:[ˈmʏnçn̩] 和 [mɪŋ(ː)ɐ] 其中一些我需要删除。示例:[3] 和 [4]

如何循环遍历字符串,删除包含数字的括号,同时保留不包含数字的括号?

期望的输出: “慕尼黑(/ˈmjuːnɪk/MEW-nik;德语:München [ˈmʏnçn̩](听);奥地利-巴伐利亚语:Minga [ˈmɪŋ(ː)ɐ];拉丁语:Monachium)是巴伐利亚州的首都和人口最多的城市。人口约 150 万,是德国第三大城市。”

我在网上查看了一些引用资料,但我发现的所有引用资料似乎都没有为我想要做的事情提供解决方案。不起作用的示例: how can i remove chars between indexes in a javascript string --- Replacing any content inbetween second and third underscore --- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split --- https://www.digitalocean.com/community/tutorials/how-to-index-split-and-manipulate-strings-in-javascript --- https://www.geeksforgeeks.org/how-to-remove-a-character-from-string-in-javascript/

最佳答案

您可以使用.replace()使用正则表达式 /\[\d+\]/g 来匹配方括号内的所有数字序列,然后您可以将其替换为空字符串 (''):

const cityInfo = "Munich (/ˈmjuːnɪk/ MEW-nik; German: München [ˈmʏnçn̩] (listen);[3] Austro-Bavarian: Minga [ˈmɪŋ(ː)ɐ]; Latin: Monachium) is the capital and most populous city of Bavaria. With a population of around 1.5 million,[4] it is the third-largest city in Germany.";

const res = cityInfo.replace(/\[\d+\]/g, '');
console.log(res);

关于javascript - 如何删除 [ 和 ] 以及之间的任何内容 (javascript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59241433/

相关文章:

javascript - 防止孤儿

javascript - 嵌套循环 JavaScript

javascript - React js 与 redux fetch 总是返回一个空的 json

ios - 无法推断通用参数 S

javascript - 以 px 为单位获取最高值 - JQuery

C 程序 : Update unsigned char pointer array with function

python - 从scrapy中提取数据到数组中

arrays - 如何为可变大小的数组创建固定的结构头

Java 字符串池测试不起作用

java - 从同一输入行读取整数和字符串(java)