【问题标题】:Trouble With .replace() - Only Works With First Matched Character?.replace() 的问题 - 仅适用于第一个匹配的字符?
【发布时间】:2010-11-04 20:30:32
【问题描述】:

我正在尝试在我的 jQuery 脚本中添加一个函数,该函数根据其 alt 属性为 img 构建完整的 src 路径。这个想法是使代码尽可能精简,以便处理它的非技术人员不会破坏任何东西;他们所要做的就是正确设置 alt 属性,然后由脚本自动构建路径的其余部分。

无论如何,我的文件名包含连字符,为了更加万无一失,我希望允许 alt 属性中的空格被 src 属性中的连字符替换。麻烦的是,.replace() 命令似乎只对第一个匹配的字符起作用,所以如果我在 alt 属性中有三个词来描述 img,第二个空格不会被替换并且 img 路径中​​断。

这是有问题的代码:

<div class="copy"><img alt="three word alt" /></div>

<script>
    $('div.copy').find('img').each(function() {
        $(this).attr('src','/images/'+$(this).attr('alt').replace(' ','-')+'.png');
    });
</script>

最终结果应该是

<img src="/images/three-word-alt.png" alt="three word alt" />

但结果却是这样的:

<img src="/images/three-word alt.png" alt="three word alt" />

有没有更好的方法?

【问题讨论】:

    标签: jquery replace


    【解决方案1】:

    在这里使用/g,像这样:

    $('div.copy').find('img').each(function() {
        $(this).attr('src','/images/'+$(this).attr('alt').replace(' '/g,'-')+'.png');
    });
    //or the regex version:
    $('div.copy').find('img').each(function() {
        $(this).attr('src','/images/'+$(this).attr('alt').replace(/ /g,'-')+'.png');
    });
    

    /gglobal modifier 以匹配所有匹配项,而不是仅匹配第一个匹配项(默认值)...与大多数其他语言相比,JavaScript 在这方面的行为有点奇怪。

    【讨论】:

      【解决方案2】:

      String.replace() 仅在第一个参数是字符串文字时才进行一次替换。改为使用正则表达式作为您的第一个参数。示例:

      $(this).attr('src','/images/'+$(this).attr('alt').replace(/ /g,'-')+'.png');
      

      $(this).attr('src','/images/'+$(this).attr('alt').replace(/\s/g,'-')+'.png');
      

      【讨论】:

      • 属性中不需要/m :)
      • @Nick Craver:啊,你说得对。我的脑海里有它是一个文本节点。正在编辑...
      【解决方案3】:

      应该做的伎俩。

      $(this).attr('src','/images/'+$(this).attr('alt').replace(/\s/g,'-')+'.png');
      

      【讨论】:

      • @thejh:确实:p 复制/粘贴失败是最好的。
      猜你喜欢
      • 2022-12-02
      • 2021-12-08
      • 1970-01-01
      • 2013-06-15
      • 1970-01-01
      • 1970-01-01
      • 2018-09-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多