sam orten
sam orten

Reputation: 206

How to replace space and comma with "-" operator?

In this code, I want to replace comma and spaces with (-) operator. If keyword is java developer, hibernate, struts, and city is delhi, noida, mumbai, how can I do this? Also at the comma and space would not be shown in the URL eg.. ,.

$("#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;
});

Upvotes: 0

Views: 282

Answers (2)

Mohammad
Mohammad

Reputation: 21489

Replace all comma and space with dash and then remove last dash from string.

$("#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, ">

Upvotes: 2

Harshit Tailor
Harshit Tailor

Reputation: 3281

Check this

$("#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;
    });

Upvotes: 1

Related Questions