Categories
JavaScript Answers

How to Strip All Punctuation from a String in JavaScript Using Regex?

Sometimes, we want to strip all punctuation from a JavaScript string with a regex.

In this article, we’ll look at how to strip all punctuation from a JavaScript string with regex.

Use the String.prototype.replace Method

We can use the JavaScript string replace method to get all the parts of a string matching a regex pattern and replace them with what we want.

For instance, we can write:

const s = "This., -/ is #! an $ % ^ & * example ;: {} of a = -_ string with `~)() punctuation";
const punctuationless = s
  .replace(/[.,/#!$%^&*;:{}=-_`~()]/g, "")
  .replace(/s{2,}/g, " ");
console.log(punctuationless)

We have the s string with lots of punctuation marks we want to remove.

Next, we call replace the first time with a regex that has all the punctuation marks that we want to remove inside.

The g flag indicates we match all instances in the string that matches the given pattern.

And we replace them all with an empty string as we indicate with the 2nd argument.

Then we call replace again with a regex that matches 2 or more whitespaces.

And we replace those whitespaces with one whitespace.

Therefore, punctuationless should be ‘This is an example of a string with punctuation’ .

Conclusion

We can use the JavaScript string replace method with a regex that matches the patterns in a string that we want to replace.

So we can use it to remove punctuation by matching the punctuation and replacing them all with empty strings.

Categories
JavaScript Answers

How to Check if a Background Image is Loaded with JavaScript?

Sometimes, we want to check if a background image is loaded with JavaScript.

In this article, we’ll look at how to check if a background image is loaded on a page with JavaScript.

Listen to the load Event

We can listen to the load event of a background image to see if it’s loaded.

If it’s loaded, then we can set the background image to the image with the same URL as the background image.

For instance, we can write:

const imageUrl = "https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png";
const bgElement = document.querySelector("body");
let preloaderImg = document.createElement("img");
preloaderImg.src = imageUrl;
`
preloaderImg.addEventListener('load', (event) => {
  bgElement.style.backgroundImage = `url(${imageUrl})`;
  preloaderImg = null;
});

We have the imageUrl with the image we want to load as the background image.

Then we get the body element with document.querySelector .

And then we create the preloaderImg element with document.createElement with the image we want to preload.

Next, we set the preloaderImg.src to imageUrl .

Then we call addEventListener on preloaderImg with 'load' as the first argument to watch for the preloaderImg loading.

The callback will run when it’s loaded.

And so we can set the bgElement.style.backgroundImage to set the background image to the image that’s loaded in the preloaderImg element.

And then we set preloaderImg to null to clear the preloaded image.

Now we should see the background image loaded in our page.

Conclusion

We can listen to the load event of an image element to see if an image is loaded.

Then once it’s loaded, we can use the image URL of the preloaded image to set the background image of the page.

Categories
JavaScript Answers

How to Get HTML5 Local Storage Keys with JavaScript?

Sometimes, we want to get the keys of the items that we stored in our browser’s local storage in our web app.

In this article, we’ll look at how to get the keys of the items stored in local storage with JavaScript.

Use the Object.entries Method

We can use the Object.entries method to get the keys and values of the items stored in local storage.

For instance, we can write:

localStorage.setItem('foo', 1)
localStorage.setItem('bar', 2)
const entries = Object.entries(localStorage)
console.log(entries)

Then entries is:

[
  [
    "foo",
    "1"
  ],
  [
    "bar",
    "2"
  ]
]

since Object.entries returns an array of key-value pair arrays in the localStorage object.

We use localStorage.setItem with the key and value of the item we want to store as arguments respectively.

Use the Object.keys Method

Also, we can use the Object.keys method to get the keys of the items that are stored in local storage.

For instance, we can write:

localStorage.setItem('foo', 1)
localStorage.setItem('bar', 2)
const keys = Object.keys(localStorage)
console.log(keys)

Then keys is [“foo”, “bar”] .

Use the localStorage.key Method

Another way to get all the keys of the items stored in local storage is to use the localStorage.key method.

We can use it along with the localStorage.length property to create an array to populate the keys with.

localStorage.length has the number of items stored in local storage.

To use them, we can write:

localStorage.setItem('foo', 1)
localStorage.setItem('bar', 2)
const keys = [...Array(localStorage.length)].map((o, i) => {
  return localStorage.key(i);
})
console.log(keys)

We spread the empty array with length localStorage.length , spread that into a new array, then call map with a callback to return the key that we get by calling localStorage.key with the i index.

As a result, keys is also [“foo”, “bar”] .

Conclusion

There’re several ways we can use the get the items stored in local storage with JavaScript.

Categories
JavaScript Answers

How to Use Lodash to Find and Return an Object from a JavaScript Array?

Sometimes, we want to use Lodash to find and return an object from a JavaScript array.

In this article, we’ll look at how to use Lodash to find and return an object from a JavaScript array.

Using the find Method

We can use the find method to find an object with a predicate function that returns the condition of the object we’re looking for.

For instance, we can write:

const arr = [{
    description: 'object1',
    id: 1
  },
  {
    description: 'object2',
    id: 2
  },
  {
    description: 'object3',
    id: 3
  },
  {
    description: 'object4',
    id: 4
  }
]

const obj = _.find(arr, (o) => {
  return o.description === 'object3';
});
console.log(obj)

We pass in the array to search as the first argument.

And we pass in the predicate function that returns the condition of the object we’re looking for as the 2nd argument.

Therefore, obj is:

{description: "object3", id: 3}

We can also pass in an object as the 2nd argument to search for an object with the property with the given value:

const arr = [{
    description: 'object1',
    id: 1
  },
  {
    description: 'object2',
    id: 2
  },
  {
    description: 'object3',
    id: 3
  },
  {
    description: 'object4',
    id: 4
  }
]

const obj = _.find(arr, {
  description: 'object3'
});
console.log(obj)

And we can pass in an array with the property key and value to do the same search:

const arr = [{
    description: 'object1',
    id: 1
  },
  {
    description: 'object2',
    id: 2
  },
  {
    description: 'object3',
    id: 3
  },
  {
    description: 'object4',
    id: 4
  }
]

const obj = _.find(arr, ['description', 'object3']);
console.log(obj)

They all get the same result as the first example.

Conclusion

We can use the Lodash find method to find the object with the given condition in an array.

Categories
JavaScript Answers

How to Retrieve the Text of the Selected option Element in a select Element with JavaScript?

Sometimes, we want to retrieve the text of the selected option element in a select element with JavaScript.

In this article, we’ll look at how to retrieve the text of the selected option element in a select element with JavaScript.

Use the selectedIndex Property

We can get the index of the selected item with the selectedIndex property.

Then we can use the text property to get the text of the selected item.

For instance, if we have the following HTML:

<select>
  <option value="1">apple</option>
  <option value="2" selected>orange</option>
</select>

Then we can write the following JavaScript code to get the selected item from the select element:

const getSelectedText = (el) => {
  if (el.selectedIndex === -1) {
    return null;
  }
  return el.options[el.selectedIndex].text;
}

const select = document.querySelector('select')
const text = getSelectedText(select);
console.log(text)

We create the getSelectedText function that takes an element as the parameter.

Then we check if selectedIndex is -1.

If it’s -1, then nothing is selected and we return null .

Otherwise, we get the options with el.options .

And then we get the selected option by passing in the el.selectedIndex into the square brackets.

Finally, we get the text property to get the text of the selected option element.

Therefore, the console log should log 'orange' .

Conclusion

We can retrieve the text of a selected option element with the selectedIndex and text properties.