【问题标题】:how do I replace all string including square bracket in javascript [closed]如何在javascript中替换所有字符串,包括方括号[关闭]
【发布时间】:2014-02-15 08:38:02
【问题描述】:

我想将 html 中的所有 animal[0] 替换为 animal[1]。 但我不想在同一个 html 中将 tiger[0] 替换为 tiger[1]

例如,

<input type="hidden" name="animal[0].tiger[0].prey"/>

<input type="hidden" name="animal[1].tiger[0].prey"/>

【问题讨论】:

  • 你有没有尝试过?似乎您甚至不需要正则表达式来执行此操作,除非您没有提到更多...

标签: javascript jquery regex


【解决方案1】:

你可以使用这些

  1. 使用属性选择器 [name^="animal[0]"] ,它将选择名称属性值在开头的标签 animal[0](^ is for represent at the start)。

  2. each() 方法遍历名称以animal[0] 开头的每个输入标签。

  3. 使用 replace()animal[0] 替换为animal[1]


$('input[name^="animal[0]"]').each(function(){
    this.name=this.name.replace('animal[0]', 'animal[1]')
});

【讨论】:

  • “试试这个”没有解释代码;)
  • 我不知道如何感谢您的快速回答。你很有帮助。谢谢。
  • @crzhacko : 很高兴为您提供帮助 :)
【解决方案2】:
var res = htmlString.replace('animal[0', 'animal[1');

【讨论】:

  • 请解释您发布的所有答案。如果 OP 不知道如何获取输入元素以对其进行替换怎么办?
  • @RUJordan IOW 这个答案所做的只是需要做的一小部分,我们不知道提问者 可以 自己做多少。
  • @JanDvorak 绝对正确
  • @RUJordan,OP 所说的只是替换。就这么简单,有什么问题?
  • @hwnd 无论是单行答案还是答案小说都没有关系。所有好的答案都有解释。哪怕只是几句话。它会带来不同。
猜你喜欢
  • 1970-01-01
  • 2013-01-04
  • 1970-01-01
  • 2023-03-05
  • 1970-01-01
  • 2018-12-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多