Reputation: 1895
HI all i have some where there is Departments and department has some data like this
Department
Casual shoe
formal shoe
sports shoe
so i want to write an if condition where i should write an if condition like this
<script type="text/javascript">
$(document).ready(function () {
$.getJSON("/api/ProductLayout", function (data) {
$.each(data, function (idx, ele) {
$("<img/>").attr({ src: ele.ImageURL }).appendTo("#makeMeScrollable");
$("#makeMeScrollable").append('<span>' + ele.ProductName + '</span><h4>' + ele.Price + '$' + '</h4>');
if (ele.Department == "Shoes") {
alert(2);
//$(".img_main").empty();
$("<img/>").attr({ src: ele.ImageURL }).appendTo("#Watches");
$("#Watches").append('<span>' + ele.ProductName + '</span><h4>' + ele.Price + '$' + '</h4>');
}
else if (ele.Department = "Wallets") {
alert(3);
$("<img/>").attr({ src: ele.ImageURL }).appendTo("#BackPacks");
$("#BackPacks").append('<span>' + ele.ProductName + '</span><h4>' + ele.Price + '$' + '</h4>');
}
else if (ele.Department = "Belts") {
alert(4);
$("<img/>").attr({ src: ele.ImageURL }).appendTo("#Belts");
$("#Belts").append('<span>' + ele.ProductName + '</span><h4>' + ele.Price + '$' + '</h4>');
}
});
});
});
</script>
now i ant to write an if condition for shoe where if (ele.Department == "Shoes") i should get all the data of deaprtments which has "shoe" in it,jow can i write an condition for this
Upvotes: 0
Views: 233
Reputation:
I think you could use regular expressions:
this tests for shoes case insensitive. (match also "shoesprostore")
if (/shoes/i.test(ele.Department)) {
}
this tests for the word shoes case insensitive. (match "Big Shoes" and "Small Shoes") (edit 4)
if (/\bshoes\b/i.test(ele.Department)) {
}
edit:
this tests for the words shoe and shoes case insensitive.
if (/\bshoes?\b/i.test(ele.Department)) {
}
\b : start and finish of a word
? : the previous character may or may not be present
i (after the sencond /) : case insensitive
look here for more http://www.w3schools.com/jsref/jsref_obj_regexp.asp
:)
edit 2:
corrected grammar inconsistencies thanks to my friend SandMan
edit 3:
maybe you could save the regex in global scope (before the $(document).ready(...)
statement) using
var shoeTest = /shoes/i;
then
if (shoeTest.test(...))
Upvotes: 1
Reputation: 10995
To answer you question about finding a substring..
I will try:
if(variableInQuestion.indexOf("shoes")!=-1)
{
}
And two of your if conditions use = not == you probably want to fix that.
UPDATE:
Looking at your question again..
"Formal shoes"
"Casual shoes"
Is it possible that you want an endsWith("shoes")
method?
If so:
endsWith in JavaScript
Upvotes: 2