Categories
JavaScript Answers

How to Check if a JavaScript String is Entirely Made of the Same Substring?

We can use the indexOf method to return the index of the first instance of the substring in a string.

Therefore, we can use that to check if a string is repeated by checking if the index of the substring after the first instance is different from the length of the string.

To do this, we can write:

const check = (str) => {
  return (str + str).indexOf(str, 1) !== str.length;
}
console.log(check('abcabc'))
console.log(check('abc123'))

We find the index of str by starting the search from index 1 to see if it’s different from str.length .

If it is, that means str is repeated in the string once.

Therefore, the first console log is true and the second console log is false .

Use Regex Capturing Group

A more versatile way to search for repeated strings is to use regex capturing groups.

For instance, we can write:

const check = (str) => {
  return /^(.+)\1+$/.test(str)
}
console.log(check('abcabc'))
console.log(check('abcabcabc'))
console.log(check('abc123'))

to check for repeated substrings with check by checking ifstr is repeated throughout the string.

Therefore, the first 2 console logs log true and the last one logs false .

Categories
JavaScript Answers

How to Find the Size of Local Storage with JavaScript?

We can convert our browser’s local storage object into a blob to get the size of it.

To do this, we write:

const {
  size
} = new Blob(Object.values(localStorage))
console.log(size)

We call Object.values with localStorage to get an array of values of our local storage.

Then we pass that into the Blob constructor so that we can use the size property of it to get the size.

Get the Size in Kilobytes

To get the size in kilobytes, we can write our own function to calculate the number of bytes stored in local storage and convert that to kilobytes.

For example, we can write:

const localStorageSpace = () => {
  let allStrings = '';
  for (const key of Object.keys(window.localStorage)) {
    allStrings += window.localStorage\[key\];
  }
  return allStrings ? 3 + ((allStrings.length \* 16) / (8 \* 1024)) + ' KB' : 'Empty (0 KB)';
};

console.log(localStorageSpace())

We define the localStorageSpace function that concatenates all the strings together into the allStrings string.

Then we calculate the size of it by getting the length of it, multiply by 16.

And then we divide it by 8 * 1024 to convert it into kilobytes.

Finally, we add 3 to it.

Categories
JavaScript Answers

How to Convert a JavaScript Array into a String?

One way to convert a JavaScript array into a string is to concatenate an empty string after it.

For instance, we can write:

const arr = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday']
const str = arr + ""
console.log(str)

Then str is:

'Sunday,Monday,Tuesday,Wednesday,Thursday'

Use the Array.prototype.toString Method

Another way to convert a JavaScript array into a string is to use the JavaScript array toString method.

For example, we can write:

const arr = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday']
const str = arr.toString();
console.log(str)

Then we get the same result as before.

Use the Array.prototype.join Method

Another way to convert a JavaScript array into a string is to use the JavaScript array join method.

We pass in a delimiter to join the strings in the array with and it’ll return a stirring with all the string array entries joined together.

For example, we can write:

const arr = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday']
const str = arr.join(", ");
console.log(str)

And str is:

'Sunday, Monday, Tuesday, Wednesday, Thursday'
Categories
JavaScript Answers

How to Set Boolean Values in JavaScript LocalStorage?

We can only store strings as values in local storage.

Therefore, boolean values are converted to strings.

To check for them, we can write:

localStorage.setItem('value', true)  
const value = localStorage.getItem('value');  
console.log(JSON.parse(value) === true);

We call setItem to store a boolean value with the 'value' key.

Then we get the item with the 'value' key with getItem .

Next, we call JSON.parse to parse that value back into a boolean.

And we check that value with === to see if it equals to true exactly.

The console log logs true so we know value is parsed as true .

We can also check the string directly.

For instance, we can write:

localStorage.setItem('value', true)  
const value = localStorage.getItem('value');  
console.log(value === 'true');

to compare value with 'true' with === .

And we also get true logged.

Categories
JavaScript Answers

How to Calculate the Day of the Year with JavaScript?

We can calculate the day of the year with JavaScript with some native date methods.

For instance, we can write:

const now = new Date(2021, 11, 3);
const start = new Date(2021, 0, 0);
const diff = (now - start) + ((start.getTimezoneOffset() - now.getTimezoneOffset()) * 60 * 1000);
const oneDay = 1000 * 60 * 60 * 24;
const day = Math.floor(diff / oneDay);
console.log(day);

We have the now and start date where now is the date we want to calculate the difference from start .

Then we calculate the diff difference by subtract now from start and add the time zone offsets differences to correct discrepancies because of time zone differences.

Next, we calculate the number of milliseconds in a day with the oneDay variable.

Next, we calculate the number of days difference between now and start by dividing diff with oneDay and then take the floor of the quotient with Math.floor .

And then we log the day result.

day should be 337 according to the console log.