jquery replace不适用于单引号

Ris*_*isu 3 jquery jstl drop-down-menu

我试图在选择框中删除我的选项中的单引号,但下面似乎没有工作:

$(function(){
  $("#agencyList").each(function() {
    $("option", $(this)).each(function(){
      var cleanValue = $(this).text();
      cleanValue.replace("'","");
      $(this).text(cleanValue);
    });
  });
});
Run Code Online (Sandbox Code Playgroud)

它仍然有单引号.select是使用JSTL forEach循环构建的.任何人都可以看到可能出错的地方?

Rob*_*b W 8

您必须使用分配新值cleanValue = cleanValue.replace(...).此外,如果要替换所有单引号,请使用全局RegEx :( /'/g替换所有出现的单引号):

$(function(){
  $("#agencyList").each(function() {
    $("option", this).each(function(){
      var cleanValue = $(this).text();
      cleanValue = cleanValue.replace(/'/g,"");
      $(this).text(cleanValue);
    });
  });
});
Run Code Online (Sandbox Code Playgroud)

另一个调整:

  • 替换$(this)this,因为没有必要将this对象包装在jQuery对象中.
  • 您的代码可以进一步优化我合并两个选择器:

    $(function(){
      $("#agencyList option").each(function() {
          var cleanValue = $(this).text();
          cleanValue = cleanValue.replace(/'/g,"");
          $(this).text(cleanValue);
      });
    });
    
    Run Code Online (Sandbox Code Playgroud)