Categories
JavaScript Answers

How to Check if a JavaScript String Contains a Substring in a Case Insensitive Manner?

Sometimes, we may want to check if a substring is in a JavaScript string in a case-insensitive manner.

In this article, we’ll check if a JavaScript string has a substring in a case-insensitive manner.

String.prototype.toLowerCase and String.prototype.indexOf

We can convert both the string and the substring we’re checking for the lower case to check if a substring is in a JavaScript string is in a case-insensitive manner.

For instance, we can write:

const includes = 'ABCDE'.toLowerCase().indexOf("abc".toLowerCase()) !== -1  
console.log(includes)

We call toLowerCase on 'ABCDE' and 'abc' to convert them both to lower case.

And then we call indexOf to check if “abc”.toLowerCase() to if included in 'ABCDE' in a case-insensitive manner.

Since 'abc' is in 'ABCDE' when they’re compared in a case-insensitive manner, indexOf should return an index other than -1.

And so includes is true .

Case-Insensitive Regex Search

We can also do a case-insensitive regex search in our code.

For instance, we can write:

const includes = /abc/i.test('ABCDE')  
console.log(includes)

The i flag lets us search for a pattern in the string we pass into test in a case-insensitive manner.

And so includes is also true in this example.

Case-Insensitive Regex Search with RegExp Constructor

Alternatively, we can do a case-insensitive regex search with the RegExp constructor.

For instance, we can write:

const includes = new RegExp("abc", "i").test('ABCDE')  
console.log(includes)

to do the same as we did before.

String.prototype.toLowerCase and String.prototype.includes

We can also substitute the indexOf method in the first example with includes .

Using the includes method, we don’t have to compare against -1.

Instead, we get true if the substring is included in a string and false otherwise.

So we can write:

const included = 'ABCDE'.toLowerCase().includes("abc".toLowerCase())  
console.log(included)

We convert them both the string and substring to lower case as usual, but we use includes to check if the substring we pass into includes is included in 'ABCDE' .

And so we should get the same result as before.

String.prototype.toLocaleLowerCase and String.prototype.includes

If we’re checking a JavaScript substring with a string that has text other than English, we may want to use the toLocaleLowerCase method since it works with non-English locales.

For instance, we can write:

const included = 'ABCDE'.toLocaleLowerCase().includes("abc".toLocaleLowerCase())  
console.log(included)

And we get the same result as before.

Conclusion

We can use various string or regex methods to check whether a substring is included in a JavaScript string in a case insensitive manner.

Categories
JavaScript Answers

How to Initialize a JavaScript Date to Midnight?

Sometimes, we may want to set a JavaScript date to midnight.

In this article, we’ll look at how to initialize a JavaScript date to midnight.

Date.prototype.setHours

We can use the setHours method to set the hour of the date to midnight.

For instance, we can write:

const d = new Date();  
d.setHours(0, 0, 0, 0);  
console.log(d)

We call setHours with the hours, minutes, seconds, and milliseconds all set to 0 to set the date d to midnight of the same date as the original date d .

The change mutates the d object.

So we see that d is midnight of the current date from the console log.

To set a date to tomorrow’s midnight, we can write:

const d = new Date();  
d.setHours(24, 0, 0, 0);  
console.log(d)

The first argument, which is the hours argument, is 24 instead of 0.

And from the console log, we should see that the date is the next day midnight.

If we want to make a copy of the date, we can pas the date to the Date constructor:

const d = new Date(new Date().setHours(0, 0, 0, 0));  
console.log(d)

Date.prototype.setUTCHours

If we want to work with UTC times, we can use the setUTCHours method to set a time to midnight.

For instance, we can write:

const d = new Date();  
d.setUTCHours(0, 0, 0, 0);  
console.log(d)

to set a date to midnight UTC.

moment.js

The moment.js library lets us set a date to midnight with the startOf method.

For instance, we can write:

const d = moment().startOf('day');  
console.log(d)

We call startOf with 'day' to set the moment object’s date-time to midnight of the same date that the moment date is on.

Conclusion

We can set a JavaScript date to midnight with native JavaScript date methods.

Also, we can use moment.js to do the same thing.

Categories
JavaScript Answers

How to Wait Until All Promises Complete Even If Some Are Rejected?

Sometimes, we may want to wait until all promises to complete but we may want to proceed regardless of whether some promises are rejected or not.

In this article, we’ll look at how to wait until all promises are completed even if some are rejected.

Promise.allSettled

The Promise.allSettled method lets us proceed with running the then callback regardless of whether all promises are complete.

For instance, we can write:

Promise.allSettled([
  Promise.resolve(1),
  Promise.resolve(2),
  Promise.reject(3),
]).then(([result1, result2, result3]) => {
  console.log(result1, result2, result3)
});

Then result1 is {status: “fulfilled”, value: 1} .

result2 is {status: “fulfilled”, value: 2} .

And result3 is {status: “rejected”, reason: 3} .

status has the status of each promise.

And value has the resolved value if the promise is resolved.

And reason has the rejected value if the promise is rejected.

We can also write the same code with the async and await syntax.

For instance, we can write:

(async () => {
  const [result1, result2, result3] = await Promise.allSettled([
    Promise.resolve(1),
    Promise.resolve(2),
    Promise.reject(3),
  ])
  console.log(result1, result2, result3)
})()

And we get the same values as before for result1 , result2 , and result3 .

Promise.all with map

We can call map on the promise array.

Then we pass in a callback that calls catch on any promise that are rejected.

The catch callback only runs when a promise is rejected, so we either return the promise itself if catch isn’t run.

Otherwise, we return a promise with the catch callback run.

So we can write:

Promise.all(
    [
      Promise.resolve(1),
      Promise.resolve(2),
      Promise.reject(3),
    ]
    .map(p => p.catch(e => e))
  )
  .then(([result1, result2, result3]) => {
    console.log(result1, result2, result3)
  });

We call map with p => p.catch(e => e) to return any promises that are rejected with a promise that’s caught.

In the catch callback, we return the rejection reason.

Then in the then callback, we can destructure the promise results as usual.

So we get that result1 is 1.

result2 is 2.

And result3 is 3.

We can write tyhe same code with async and await by writing:

(async () => {
  const [result1, result2, result3] = await Promise.all([
      Promise.resolve(1),
      Promise.resolve(2),
      Promise.reject(3),
    ]
    .map(p => p.catch(e => e))
  )
  console.log(result1, result2, result3)
})()

And we get the same result as before.

Conclusion

The Promise.allSettled method is the best way to run code after a promise is run regardless of the outcomes of the promises that are run.

If we don’t want to use that, we can also use Promise.all with map and catch .

Categories
JavaScript Answers

How to Set the Value of an Input Field with JavaScript?

One way to set the value of an input field with JavaScript is to set the value property of the input element.

For instance, we can write the following HTML:

<input id='mytext'>

Then we can set the value property of the input by writing:

document.getElementById("mytext").value = "My value";

Call the setAttribute Method

Also, we can call the setAttribute method to set the value attribute of the input element.

For instance, we can write:

document.getElementById("mytext").setAttribute('value', 'My value');

We call setAttribute with the attribute name and value to set the value attribute to 'My value' .

Setting the value Property of an Input in a Form

We can also get the input element by using the document.forms object with the name attribute value of the form and the name attribute value of the input element.

For example, we can write the following HTML:

<form name='myForm'>
  <input type='text' name='name' value=''>
</form>

Then we can use it by writing:

document.forms.myForm.name.value = "New value";

The form name value comes first.

Then the name value of the input element comes after it.

document.querySelector

We can use the document.querySelector method to select the input.

For instance, we can write the following HTML:

<input type='text' name='name' value=''>

Then we can write:

document.querySelector('input[name="name"]').value = "New value";

to get the element with querySelector .

We select the input with the name attribute by putting the name key with its value in the square brackets.

Categories
JavaScript Answers

How to Get a Key in a JavaScript Object by its Value?

Sometimes, we may want to get the key of a JavaScript object by its value.

In this article, we’ll look at how to get a key in a JavaScript object by its value.

Object.keys and Array.prototype.find

We can use the Object.keys method to return an array of non-inherited string keys in an object.

And we can use the JavaScript array’s find method to return the first instance of something that meets the given condition in an array.

For instance, we can write:

const object = {
  a: 1,
  b: 2,
  c: 3
}
const value = 2;
const key = Object.keys(object).find(key => object[key] === value);
console.log(key)

We have the object object that we want to search for the key in.

And value is the value of the key that we want to search for.

We get all the keys of object with Object.kets .

Then we call find with a callback that returns object[key] === value .

key is the object key being iterated through to find the key name for the given value .

Therefore, we should see that key is 'b' from the console log.

Object.keys and Array.prototype.filter

We can replace the find with filter and destructure the result from the array returned by filter .

For instance, we can write:

const object = {
  a: 1,
  b: 2,
  c: 3
}
const value = 2;
const [key] = Object.keys(object).filter(key => object[key] === value);
console.log(key)

And we get the same result for key as in the previous example.

Object.entries and Array.prototype.find

We can use the Object.entries method to return an array of arrays of key-value pairs of an object.

Therefore, we can use the returned array to find the key of the object with the given value.

For instance, we can write:

const object = {
  a: 1,
  b: 2,
  c: 3
}
const value = 2;
const [key] = Object.entries(object).find(([, val]) => val === value);
console.log(key)

We call find with a callback that has the parameter with the val variable destrutured from the parameter.

val has the value of the in the key-value pair array.

So when we return val === value , we return the same boolean expression as the first example.

From the returned result of find , we can get the key of from the returned key-value pair by destructuring it.

And so we get the same value of key logged in the console log.

Conclusion

We can find a key that has the given value by using native JavaScript object methods.