This question already has answers here:
Methods in ES6 objects: using arrow functions
(6 answers)
Closed 3 years ago.
This is my code
const products =
[
{
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto",
"coefficient":2,
"price": () => 2000 * this.coefficient
},
{
"id": 2,
"title": "qui est esse",
"body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla",
"coefficient":3,
"price": () => 2000 * this.coefficient
},
]
I want to return the price depends on the coefficient, but when i excute
products[0].price() // return NaN
how can i fix that ?
Thanks.
This is due to the way that arrow functions handle the this scope. In this case, replacing the arrow function (() => this.something) with a traditional JS function (function() { return this.something; }) will solve your problem.
The this in an arrow function refers to the class scope, that is an empty object; in that case, yo refer to the the object scope you must use the full function syntax.
Try this:
products = [
{
id: 1,
title:
"sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
body:
"quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto",
coefficient: 2,
price: function() {
return 2000 * this.coefficient;
}
},
{
id: 2,
title: "qui est esse",
body:
"est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla",
coff: 3,
price: function() {
return 2000 * this.coefficient;
}
}
];
console.log(products[0].price()) // 4000
console.log(products[1].price()) // 6000
For the arrow functions, value of this is not based on the object reference using which the function was executed. Rather it uses the this reference from the closure where it was declared. Check the documentation here on MDN. In your scenario this.coefficient would be undefined, which when multiplied with 2000 results in NaN.
You can change the arrow functions to proper functions if you need this to refer to the object reference on which price function was called. Changed code should be something like this:
products = [
{
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto",
"coefficient":2,
"price": function() { return 2000 * this.coefficient; }
}
];
You can use this :
const products =
[
{
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto",
"coefficient": 2,
price() {
return 2000 * this.coefficient
}
},
{
"id": 2,
"title": "qui est esse",
"body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla",
"coefficient": 3,
price() {
return 2000 * this.coefficient
}
},
]
Related
Hope you are doing well.
[ {
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
},
{
"userId": 2,
"id": 2,
"title": "qui est esse",
"body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"
},
{
"userId": 3,
"id": 3,
"title": "ea molestias quasi exercitationem repellat qui ipsa sit aut",
"body": "et iusto sed quo iure\nvoluptatem occaecati omnis eligendi aut ad\nvoluptatem doloribus vel accusantium quis pariatur\nmolestiae porro eius odio et labore et velit aut"
},
]
Considering there are multiple objects for each userId and I want to group them together in the below format.
const json2 = {
1: [{},{},{}],
2:[{},{},{}],
3:[{},{},{}],
}
Any help will be appreciated.
Thanks in Advance
You can do it using the reduce function, but next time please provide what you tried before asking.
const input = [{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
},
{
"userId": 2,
"id": 2,
"title": "qui est esse",
"body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"
},
{
"userId": 3,
"id": 3,
"title": "ea molestias quasi exercitationem repellat qui ipsa sit aut",
"body": "et iusto sed quo iure\nvoluptatem occaecati omnis eligendi aut ad\nvoluptatem doloribus vel accusantium quis pariatur\nmolestiae porro eius odio et labore et velit aut"
},
];
const output = input.reduce((acc, el) => {
acc[el.userId]??=[];
acc[el.userId].push(el);
return acc;
}, {})
console.log(output);
I made a list (j_list) contain some post. I want a way to access on each body property present on the list.
My goal is find if a specific word exist on body property string.
const j_list =[
const post = {
"postId": 1,
"id": 1,
"name": "id labore ex et quam laborum",
"email": "Eliseo#gardner.biz",
"body": "laudantium enim quasi est quidem magnam voluptate ipsam eos\ntempora quo necessitatibus\ndolor quam autem quasi\nreiciendis et nam sapiente accusantium"
},
const post = {
"postId": 1,
"id": 2,
"name": "quo vero reiciendis velit similique earum",
"email": "Jayne_Kuhic#sydney.com",
"body": "est natus enim nihil est dolore omnis voluptatem numquam\net omnis occaecati quod ullam at\nvoluptatem error expedita pariatur\nnihil sint nostrum voluptatem reiciendis et"
},
const post = {
"postId": 1,
"id": 3,
"name": "odio adipisci rerum aut animi",
"email": "Nikita#garfield.biz",
"body": "quia molestiae reprehenderit quasi aspernatur\naut expedita occaecati aliquam eveniet laudantium\nomnis quibusdam delectus saepe quia accusamus maiores nam est\ncum et ducimus et vero voluptates excepturi deleniti ratione"
}
]
I try this on my code :
for (post in j_list){
if(post.body.includes("quasi") > -1){
console.log("This post contain that word")
} else {
console.log("This post doesn't contain any search word")
}
You are defining the array in a wrong way. Each element should be separated via a , without const post.
const j_list = [
{
"postId": 1,
"id": 1,
"name": "id labore ex et quam laborum",
"email": "Eliseo#gardner.biz",
"body": "laudantium enim quasi est quidem magnam voluptate ipsam eos\ntempora quo necessitatibus\ndolor quam autem quasi\nreiciendis et nam sapiente accusantium"
},
{
"postId": 1,
"id": 2,
"name": "quo vero reiciendis velit similique earum",
"email": "Jayne_Kuhic#sydney.com",
"body": "est natus enim nihil est dolore omnis voluptatem numquam\net omnis occaecati quod ullam at\nvoluptatem error expedita pariatur\nnihil sint nostrum voluptatem reiciendis et"
},
{
"postId": 1,
"id": 3,
"name": "odio adipisci rerum aut animi",
"email": "Nikita#garfield.biz",
"body": "quia molestiae reprehenderit quasi aspernatur\naut expedita occaecati aliquam eveniet laudantium\nomnis quibusdam delectus saepe quia accusamus maiores nam est\ncum et ducimus et vero voluptates excepturi deleniti ratione"
}
];
for (const post of j_list){
if(post.body.includes("quasi") > -1){
console.log("This post contain that word")
} else {
console.log("This post doesn't contain any search word")
}
}
Change your declaration to an array of objects, then access those objects in a loop; Example:
const j_list = [{
"postId": 1,
"id": 1,
"name": "id labore ex et quam laborum",
"email": "Eliseo#gardner.biz",
"body": "laudantium enim quasi est quidem magnam voluptate ipsam eos\ntempora quo necessitatibus\ndolor quam autem quasi\nreiciendis et nam sapiente accusantium"
},
{
"postId": 1,
"id": 2,
"name": "quo vero reiciendis velit similique earum",
"email": "Jayne_Kuhic#sydney.com",
"body": "est natus enim nihil est dolore omnis voluptatem numquam\net omnis occaecati quod ullam at\nvoluptatem error expedita pariatur\nnihil sint nostrum voluptatem reiciendis et"
}, {
"postId": 1,
"id": 3,
"name": "odio adipisci rerum aut animi",
"email": "Nikita#garfield.biz",
"body": "quia molestiae reprehenderit quasi aspernatur\naut expedita occaecati aliquam eveniet laudantium\nomnis quibusdam delectus saepe quia accusamus maiores nam est\ncum et ducimus et vero voluptates excepturi deleniti ratione"
}
];
// string includes returns a boolean
j_list.forEach(function(postel, index) {
// console.log(postel, postel.body);
if (postel.body.includes("quasi")) {
console.log("This post contain that word")
} else {
console.log("This post doesn't contain any search word")
}
});
So, my question is, can you fetch multiple posts from JSON Placeholder API, but call fetch once, and fetch 12 posts for example. This is what I did so far, but when I go into network in inspect element, I get 12 API calls, and I want it to be 1 if it is possible
const fetchPosts = (id) => {
fetch("https://jsonplaceholder.typicode.com/posts/" + id)
.then(function (response) {
return response.json();
})
.then((json) => {
var result = document.querySelector(".wrapper");
result.innerHTML += "<div class=\"posts\">" + json.title + "</div>";
});
};
for(let i = 0; i <= 12; i++) {
fetchPosts(i);
}
<div class="wrapper"></div>
The API supports a filter. You can pass a list of IDs and other properties, e.g.:
fetch('https://jsonplaceholder.typicode.com/posts?id=0&id=1&id=2&id=3&id=4&id=5&id=6&id=7&id=8&id=9&id=10&id=11')
.then((response) => response.json())
.then((json) => console.log(json));
It sends one request and returns a response containing an array of posts:
[
{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
},
{
"userId": 1,
"id": 2,
"title": "qui est esse",
"body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"
},
{
"userId": 1,
"id": 3,
"title": "ea molestias quasi exercitationem repellat qui ipsa sit aut",
"body": "et iusto sed quo iure\nvoluptatem occaecati omnis eligendi aut ad\nvoluptatem doloribus vel accusantium quis pariatur\nmolestiae porro eius odio et labore et velit aut"
},
{
"userId": 1,
"id": 4,
"title": "eum et est occaecati",
"body": "ullam et saepe reiciendis voluptatem adipisci\nsit amet autem assumenda provident rerum culpa\nquis hic commodi nesciunt rem tenetur doloremque ipsam iure\nquis sunt voluptatem rerum illo velit"
},
{
"userId": 1,
"id": 5,
"title": "nesciunt quas odio",
"body": "repudiandae veniam quaerat sunt sed\nalias aut fugiat sit autem sed est\nvoluptatem omnis possimus esse voluptatibus quis\nest aut tenetur dolor neque"
},
{
"userId": 1,
"id": 6,
"title": "dolorem eum magni eos aperiam quia",
"body": "ut aspernatur corporis harum nihil quis provident sequi\nmollitia nobis aliquid molestiae\nperspiciatis et ea nemo ab reprehenderit accusantium quas\nvoluptate dolores velit et doloremque molestiae"
},
{
"userId": 1,
"id": 7,
"title": "magnam facilis autem",
"body": "dolore placeat quibusdam ea quo vitae\nmagni quis enim qui quis quo nemo aut saepe\nquidem repellat excepturi ut quia\nsunt ut sequi eos ea sed quas"
},
{
"userId": 1,
"id": 8,
"title": "dolorem dolore est ipsam",
"body": "dignissimos aperiam dolorem qui eum\nfacilis quibusdam animi sint suscipit qui sint possimus cum\nquaerat magni maiores excepturi\nipsam ut commodi dolor voluptatum modi aut vitae"
},
{
"userId": 1,
"id": 9,
"title": "nesciunt iure omnis dolorem tempora et accusantium",
"body": "consectetur animi nesciunt iure dolore\nenim quia ad\nveniam autem ut quam aut nobis\net est aut quod aut provident voluptas autem voluptas"
},
{
"userId": 1,
"id": 10,
"title": "optio molestias id quia eum",
"body": "quo et expedita modi cum officia vel magni\ndoloribus qui repudiandae\nvero nisi sit\nquos veniam quod sed accusamus veritatis error"
},
{
"userId": 2,
"id": 11,
"title": "et ea vero quia laudantium autem",
"body": "delectus reiciendis molestiae occaecati non minima eveniet qui voluptatibus\naccusamus in eum beatae sit\nvel qui neque voluptates ut commodi qui incidunt\nut animi commodi"
}
]
Example:
fetch("https://jsonplaceholder.typicode.com/posts?id=0&id=1&id=2&id=3&id=4&id=5&id=6&id=7&id=8&id=9&id=10&id=11")
.then(res => res.json())
.then(data => {
const html = data.reduce((acc, el) => acc + "<div class=\"posts\">" + el.title + "</div>", '');
const result = document.querySelector(".wrapper");
result.innerHTML = html;
});
<div class="wrapper"></div>
JSONPlaceholder is based on JSON Server and supports pagination. You can achieve the same result with
fetch('https://jsonplaceholder.typicode.com/posts?_page=0&_limit=12')
.then((response) => response.json())
.then((json) => console.log(json));
I've been trying since this weekend implement this but no success so far.
I have a dropdown that should display items available on every event.
"id": "80773bce-7baf-49ae-8e65-328064a97116",
"title": "Sed sit qui enim corrupti magni at et voluptatum atque.",
"address": "69706 Lester Drive, Bedfordshire, Wilmington",
"guests": 70,
"budget": "65947.00",
"created_at": "2022-03-21T21:37:27.700+00:00",
"updated_at": "2022-03-21T21:37:27.700+00:00",
"is_public": false,
"description": "Fuga illo amet. Nihil omnis quae inventore repudiandae iure excepturi. Sunt necessitatibus harum culpa aliquid asperiores tenetur. Rem doloribus minus beatae officiis. Reprehenderit iure consequatur ea voluptates itaque voluptate vel dolorem reiciendis. Illo omnis et.\n \rDicta magnam et architecto ex cumque. Fugiat velit ullam deserunt perferendis consequuntur libero excepturi illum aspernatur. Quo iure libero vitae voluptatem aliquid qui dolores perspiciatis. Sed libero iusto ea odit incidunt iste libero.",
"event_date": "2022-03-21",
"start_hour": "2022-03-21T10:26:06.000Z",
"end_hour": "2022-03-21T10:26:06.000Z",
"landmark": "-11.9522,179.1757",
"location": "Laudantium veritatis animi ut quo est dolor inventore voluptate iure.",
"customer": null,
"eventType": null,
"items": [
{
"id": "70d32cee-a0fc-458a-b3e0-1bd0dbd4fdb5",
"title": "Sunt et unde eaque.",
"description": "Aut fugit voluptas explicabo animi. Illum reiciendis saepe minima dolore saepe pariatur omnis et et. Qui ratione rerum voluptatem voluptatem natus voluptatem eligendi. Iure sint et quae cumque sit neque. Similique magnam reprehenderit.",
"order": 97,
"enabled": true,
"created_at": "2022-03-21T21:37:27.702+00:00",
"updated_at": "2022-03-21T21:37:27.702+00:00"
}
],
"county": null
},
This should be the return from API.
Data is an array of objects and I must display all it's items under "eventType" line.
When I display it I must select one option and then should return only events that has that item on it's service.
So far, what I did was:
const mappedEventsData = eventsData.map((item) => {
return item.items[0];
});
And I succesfully rendered those . Then I passed it's title or id as paramater and my state is ok with that.
When I try to filter it however I cannot do it. I tried to console.log
useEffect(() => {
getData();
getEventsData();
console.log(mappedEventsData.includes(searchByTitle));
}, [searchByTitle]);
{mappedEventsData
.filter((item) => {
if (!item) return false;
return item.title.toLowerCase();
})
// .filter((item, index) => index < 3)
?.map((item) => {
return (
<option onClick={() => handleChangeSearchByEvents(item.id)} key={item.id}>
{item.title}
</option>
);
})}
and it always returns false.
How can I fix it and make it work?
I'm trying to get a case-insensitive search with two strings in JavaScript working.
Normally it would be like this:
var string="Stackoverflow is the BEST";
var result= string.search(/best/i);
alert(result);
The /i flag would be for case-insensitive.
But I need to search for a second string; without the flag it works perfect:
var string="Stackoverflow is the BEST";
var searchstring="best";
var result= string.search(searchstring);
alert(result);
If I add the /i flag to the above example it would search for searchstring and not for what is in the variable "searchstring" (next example not working):
var string="Stackoverflow is the BEST";
var searchstring="best";
var result= string.search(/searchstring/i);
alert(result);
How can I achieve this?
Yeah, use .match, rather than .search. The result from the .match call will return the actual string that was matched itself, but it can still be used as a boolean value.
var string = "Stackoverflow is the BEST";
var result = string.match(/best/i);
// result == 'BEST';
if (result){
alert('Matched');
}
Using a regular expression like that is probably the tidiest and most obvious way to do that in JavaScript, but bear in mind it is a regular expression, and thus can contain regex metacharacters. If you want to take the string from elsewhere (eg, user input), or if you want to avoid having to escape a lot of metacharacters, then you're probably best using indexOf like this:
matchString = 'best';
// If the match string is coming from user input you could do
// matchString = userInput.toLowerCase() here.
if (string.toLowerCase().indexOf(matchString) != -1){
alert('Matched');
}
Replace
var result= string.search(/searchstring/i);
with
var result= string.search(new RegExp(searchstring, "i"));
If you're just searching for a string rather than a more complicated regular expression, you can use indexOf() - but remember to lowercase both strings first because indexOf() is case sensitive:
var string="Stackoverflow is the BEST";
var searchstring="best";
// lowercase both strings
var lcString=string.toLowerCase();
var lcSearchString=searchstring.toLowerCase();
var result = lcString.indexOf(lcSearchString)>=0;
alert(result);
Or in a single line:
var result = string.toLowerCase().indexOf(searchstring.toLowerCase())>=0;
Suppose we want to find the string variable needle in the string variable haystack. There are three gotchas:
Internationalized applications should avoid string.toUpperCase and string.toLowerCase. Use a regular expression which ignores case instead. For example, var needleRegExp = new RegExp(needle, "i"); followed by needleRegExp.test(haystack).
In general, you might not know the value of needle. Be careful that needle does not contain any regular expression special characters. Escape these using needle.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");.
In other cases, if you want to precisely match needle and haystack, just ignoring case, make sure to add "^" at the start and "$" at the end of your regular expression constructor.
Taking points (1) and (2) into consideration, an example would be:
var haystack = "A. BAIL. Of. Hay.";
var needle = "bail.";
var needleRegExp = new RegExp(needle.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"), "i");
var result = needleRegExp.test(haystack);
alert(result);
ES6+:
let string="Stackoverflow is the BEST";
let searchstring="best";
let found = string.toLowerCase()
.includes(searchstring.toLowerCase());
includes() returns true if searchString appears at one or more positions or false otherwise.
If you are concerned about the "unterminated character class" case, removing all non-alphanumeric chars would be helpful:
searchstring = searchstring.replace(/[^a-zA-Z 0-9]+/g,'');
I like #CHR15TO's answer, unlike other answers I've seen on other similar questions, that answer actually shows how to properly escape a user provided search string (rather than saying it would be necessary without showing how).
However, it's still quite clunky, and possibly relatively slower. So why not have a specific solution to what is likely a common requirement for coders? (And why not include it in the ES6 API BTW?)
My answer [https://stackoverflow.com/a/38290557/887092] on a similar question enables the following:
var haystack = 'A. BAIL. Of. Hay.';
var needle = 'bail.';
var index = haystack.naturalIndexOf(needle);
I do this often and use a simple 5 line prototype that accepts varargs. It is fast and works everywhere.
myString.containsIgnoreCase('red','orange','yellow')
/**
* #param {...string} var_strings Strings to search for
* #return {boolean} true if ANY of the arguments is contained in the string
*/
String.prototype.containsIgnoreCase = function(var_strings) {
const thisLowerCase = this.toLowerCase()
for (let i = 0; i < arguments.length; i++) {
let needle = arguments[i]
if (thisLowerCase.indexOf(needle.toLowerCase()) >= 0) {
return true
}
}
return false
}
/**
* #param {...string} var_strings Strings to search for
* #return {boolean} true if ALL of the arguments are contained in the string
*/
String.prototype.containsAllIgnoreCase = function(var_strings) {
const thisLowerCase = this.toLowerCase()
for (let i = 0; i < arguments.length; i++) {
let needle = arguments[i]
if (thisLowerCase.indexOf(needle.toLowerCase()) === -1) {
return false
}
}
return true
}
// Unit test
let content = `
FIRST SECOND
"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat."
"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat."
"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat."
"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat."
"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat."
"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat."
FOO BAR
`
let data = [
'foo',
'Foo',
'foobar',
'barfoo',
'first',
'second'
]
let result
data.forEach(item => {
console.log('Searching for', item)
result = content.containsIgnoreCase(item)
console.log(result ? 'Found' : 'Not Found')
})
console.log('Searching for', 'x, y, foo')
result = content.containsIgnoreCase('x', 'y', 'foo');
console.log(result ? 'Found' : 'Not Found')
console.log('Searching for all', 'foo, bar, foobar')
result = content.containsAllIgnoreCase('foo', 'bar', 'foobar');
console.log(result ? 'Found' : 'Not Found')
console.log('Searching for all', 'foo, bar')
result = content.containsAllIgnoreCase('foo', 'bar');
console.log(result ? 'Found' : 'Not Found')
There are two ways for case insensitive comparison:
Convert strings to upper case and then compare them using the strict operator (===).
Pattern matching using string methods:
Use the "search" string method for case insensitive search.
<!doctype html>
<html>
<head>
<script>
// 1st way
var a = "apple";
var b = "APPLE";
if (a.toUpperCase() === b.toUpperCase()) {
alert("equal");
}
//2nd way
var a = " Null and void";
document.write(a.search(/null/i));
</script>
</head>
</html>
You can make everything lowercase:
var string="Stackoverflow is the BEST";
var searchstring="best";
var result= (string.toLowerCase()).search((searchstring.toLowerCase()));
alert(result);
I was trying for incase-sensitive string search and I tried
var result = string.toLowerCase().match(searchstring)
and also
var result= string.search(new RegExp(searchstring, "i"));
But I did some little modifications and that worked for me
var result = string.match(new RegExp(searchstring, "i"));
This is will either lowercase, uppercase or combination also
I noticed that if the user enters a string of text but leaves the input without selecting any of the autocomplete options no value is set in the hidden input, even if the string coincides with one in the array.
So, with help of the other answers I made this:
var $local_source = [{
value: 1,
label: "c++"
}, {
value: 2,
label: "java"
}, {
value: 3,
label: "php"
}, {
value: 4,
label: "coldfusion"
}, {
value: 5,
label: "javascript"
}, {
value: 6,
label: "asp"
}, {
value: 7,
label: "ruby"
}];
$('#search-fld').autocomplete({
source: $local_source,
select: function (event, ui) {
$("#search-fld").val(ui.item.label); // display the selected text
$("#search-fldID").val(ui.item.value); // save selected id to hidden input
return false;
},
change: function( event, ui ) {
var isInArray = false;
$local_source.forEach(function(element, index){
if ($("#search-fld").val().toUpperCase() == element.label.toUpperCase()) {
isInArray = true;
$("#search-fld").val(element.label); // display the selected text
$("#search-fldID").val(element.value); // save selected id to hidden input
console.log('inarray: '+isInArray+' label: '+element.label+' value: '+element.value);
};
});
if(!isInArray){
$("#search-fld").val(''); // display the selected text
$( "#search-fldID" ).val( ui.item? ui.item.value : 0 );
}
}