简体   繁体   English

麻烦.replace() - 只适用于第一个匹配字符?

[英]Trouble With .replace() - Only Works With First Matched Character?

I'm trying to add a function in my jQuery script that constructs a complete src path for an img based on its alt attribute. 我正在尝试在我的jQuery脚本中添加一个函数,该函数根据其alt属性为img构建一个完整的src路径。 The idea is to make the code as slim as possible so that the non-techies who handle it don't break anything; 我们的想法是尽可能使代码变得纤薄,以便处理它的非技术人员不会破坏任何东西; all they'd have to do is get the alt attribute correct and the rest of the path is constructed automagically by the script. 他们所要做的就是让alt属性正确,路径的其余部分由脚本自动构建。

Anyway, my file names include hyphens, and to make it extra foolproof I want to allow spaces in the alt attribute that would be replaced with hyphens in the src attribute. 无论如何,我的文件名包含连字符,为了使其更加万无一失,我想在alt属性中允许空格,这些空格将被替换为src属性中的连字符。 The trouble is, the .replace() command only seems to work on the first matched character, so if I have three words in the alt attribute to describe the img, the second space doesn't get replaced and the img path breaks. 麻烦的是, .replace()命令似乎只对第一个匹配的字符起作用,所以如果我在alt属性中有三个单词来描述img,则第二个空格不会被替换而img路径会中断。

Here's the code in question: 这是有问题的代码:

<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>

The end result should be 最终结果应该是

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

But instead it comes out like this: 但相反它出来是这样的:

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

Is there maybe a better way of doing this? 有没有更好的方法呢?

Use /g here, like this: 在这里使用/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');
});

/g is the global modifier to match all occurrences instead of just the first (the default)...JavaScript's a bit odd in it's behavior in that respect, compared to most other languages. /g是匹配所有匹配项的全局修饰符 ,而不仅仅是第一个(默认值)...与大多数其他语言相比,JavaScript在这方面的行为有点奇怪。

String.replace() only does one replacement if the first argument is a string literal. 如果第一个参数是字符串文字,String.replace()只进行一次替换。 Use a Regex as your first argument instead. 使用正则表达式作为您的第一个参数。 Example: 例:

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

or 要么

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

应该做的伎俩。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM