如何用“-”运算符代替空格和逗号?

时间:2018-12-20 09:58:58

标签: javascript

在这段代码中,我想用(-)运算符替换逗号和空格。如果keywordjava developer, hibernate, struts,,而citydelhi, noida, mumbai,我该怎么做?同样,逗号和空格也不会显示在URL中,例如,

$("#search").click(function(e) {
  e.preventDefault();

  str1 = $("#keyword").val();
  str2 = str1.replace(", ","-");
  keyword = str2.replace(" ", "-");

  keys1 = $("#city").val();
  keys2 = keys1.replace(", ","-");
  city = keys2.replace(" ", "-");
  window.location.href = "<?php echo base_url(); ?>" + keyword + "-in-" + city;
});

2 个答案:

答案 0 :(得分:2)

用破折号替换所有逗号和空格,然后从字符串中删除最后一个破折号。

$("#search").click(function(e){
  var str = $("#keyword").val().replace(/[,\s]+/g, '-').replace(/-$/, '');
  console.log(str);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="search">search</button>
<input type="text" id="keyword" value="java developer, hibernate, struts, ">

答案 1 :(得分:1)

检查

$("#search").click(function(e) {
      e.preventDefault();

      keyword = $("#keyword").val();
      if(keyword.length>0){
         keyword = keyword.subString(0,(keyword.length-1));
         keyword = keyword.replace(/, /g, "-");
         keyword = keyword.replace(/ /g, "-");
      }
      city = $("#city").val();
      if(keyword.length>0){
        city = city.subString(0,(city.length-1));
        city = city.replace(/, /g, "-");
        city = city.replace(/ /g, "-");
      }
      window.location.href = "<?php echo base_url(); ?>" + keyword + "-in-" + city;
    });