【问题标题】:Replace & lowercase in Jquery在 Jquery 中替换和小写
【发布时间】:2016-07-15 08:56:21
【问题描述】:

我有一个文本框,在输入文本时需要将其复制到其他文本框中,并且单词之间的间距需要用破折号替换,它应该被转换为小写。

我有下面的代码,但它不工作

$(document).ready(function() {
$('#Name').keyup(function(e) {
    var txtVal = $(this).val();
    txtVal = txtVal.toLowerCase();
    $('#URL').val(txtVal);
});

});

需要帮助,有什么办法??

【问题讨论】:

  • 这里有什么问题?
  • txtVal != taxVal - 你的变量名有错别字
  • 哦该死..我的坏:(

标签: jquery replace lowercase


【解决方案1】:

替换为小写后,将[space]全部替换为-

$(document).ready(function() {
  $('#Name').keyup(function(e) {
    var txtVal = $(this).val();
    txtVal = txtVal.toLowerCase().replace(/\s/g, '-');
    $('#URL').val(txtVal);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="Name" />
<input id="URL" />

【讨论】:

    【解决方案2】:

    将所有空白字符替换为-

    $(document).ready(function() {
      $('#Name').keyup(function(e) {
        var txtVal = $(this).val();
        txtVal = txtVal.toLowerCase().replace(/\s/g, '-');
        $('#URL').val(txtVal);
      });
    });
    

    【讨论】:

      【解决方案3】:

      您也可以按照以下步骤操作:

      1. toLowerCase()
      2. split(' ')
      3. join('-')

      代码 sn-ps:

      txtVal = txtVal.toLowerCase().split(' ').join('-');
      

      Fiddle Example

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-10
        • 1970-01-01
        • 2013-12-13
        • 2021-05-31
        • 1970-01-01
        • 1970-01-01
        • 2013-10-15
        • 2013-04-29
        相关资源
        最近更新 更多