Patrick
Patrick

Reputation: 2781

Unable to match strings with jQuery with blank space

I am trying to match a string inside another but I am not able to do it:

I want to match a string based on another string that I am typing but I get "false" when I "ask" if "Aston Martin" starts with "Aston ".

EDIT:

Note that the filter is a "as you type", and in this case, I have a blank space in the end of "Aston ".

IMPORTANT NOTE:

Based on @mplungjan answer, I had another issue regarding the blank space at the end of the filter string. Testing it, I was getting the charCode 160, so the solution I used was applying the replace to both strings:

.replace(String.fromCharCode(160), ' ')

var value = $("#brand").text();
var brand = $("#filter").val();

alert(brand.substr(0, value.length).toUpperCase() == value.toUpperCase());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div id="brand">Aston Martin</div>
<input id="filter" value="Aston ">

Upvotes: 0

Views: 508

Answers (4)

Afnan Ahmad
Afnan Ahmad

Reputation: 2542

You can try it like this:

x = "Aston Martin";

if (x.match("Aston")) {
     // Code
}

Update1:

And if you want that your string should starts with specific word and you want to match space at end you can do this:

if(x.match(/^Aston /)) {

}

Upvotes: 1

mplungjan
mplungjan

Reputation: 177786

Using indexOf == 0 will show the string beginning with the brand INCLUDING the space in the value!

var brand = $("#brand").text();
var value = $("#filter").val();

console.log(">"+brand+"<",">"+value+"<",brand.toUpperCase().indexOf(value.toUpperCase())==0);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div id="brand">Aston Martin</div>
<input id="filter" value="Aston ">

Onkeyup:

$("#filter").on("keyup", function() {
  var brand = $("#brand").text();
  brand = brand?brand.toUpperCase():"";
  var value = $("#filter").val();
  value = value?value.toUpperCase():"";
  if (brand && value) {
    console.log(brand, value,brand.indexOf(value) == 0); // same as regex /^word /
  }
  else {
    console.log("Something is empty");
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div id="brand">Aston Martin</div>
<input id="filter" value="Aston ">

Upvotes: 1

Ryad Boubaker
Ryad Boubaker

Reputation: 1501

This will work, and dont forget you have a space in the value of the input?

var value = $("#brand").text();
var brand = $("#filter").val();

alert(!!value.toUpperCase().match(brand.toUpperCase()));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div id="brand">Aston Martin</div>
<input id="filter" value="Aston ">

Upvotes: 1

Farhad Azarbarzinniaz
Farhad Azarbarzinniaz

Reputation: 739

please use this one :

value.toUpperCase().indexOf(brand.toUpperCase())>=0?true:false

Upvotes: 0

Related Questions