Categories
JavaScript Answers

How to Remove a CSS Property Using JavaScript?

Sometimes, we may want to remove a CSS property from an HTML element using JavaScript.

In this article, we’ll look at how to remove a CSS property using JavaScript.

Use the style.removeProperty Method

We can use the removeProperty method to remove a CSS property from an element.

For instance, if we have the following HTML:

<div style='background-color: green'>  
  hello  
</div>

We can remove the background-color property by writing:

const el = document.querySelector('div')  
el.style.removeProperty('background-color');

Setting a CSS Property to an Empty String

Another way to remove a CSS property from an HTML element is to set its value to an empty string.

For instance, we can write:

const el = document.querySelector('div')  
el.style.backgroundColor = ''

to remove the value of the CSS background-color property.

Conclusion

We can remove CSS properties from an object by setting to an empty string or calling the removeProperty method.

Categories
JavaScript Answers

What are Smart Ways to Truncate Long Strings in JavaScript?

Sometimes, we may want to truncate long strings in our JavaScript code.

In this article, we’ll look at some good ways to truncate long strings in JavaScript.

Using the String.prototype.substr Method

We can use the string instance’s substr method to return a substring given the start and end indexes.

For instance, we can write:

const truncate = (str, n) => {
  return (str.length > n) ? str.substr(0, n - 1) + '...' : str;
};

console.log(truncate('Lorem ipsum dolor sit amet, consectetur adipiscing elit.', 10))

We create the truncate function with the str parameter that takes the string.

n is the number of characters to truncate to.

And we return the substring returned by the substr method with the start and end indexes if the string’s length is longer than n .

Otherwise, we return the whole string.

Therefore, the console log should log 'Lorem ips…’ since we truncate the string to 10 characters in length.

String.prototype.replace Method

We can use the string replace method with a regex to truncate a string.

To use it, we write:

const truncate = (str, n) => {
  return str.replace(new RegExp(`(.{${n-1}})..+`), "$1...");
};

console.log(truncate('Lorem ipsum dolor sit amet, consectetur adipiscing elit.', 10))

We call replace with a regex that takes the n value and matches the first n-1 characters of the string.

Then in the 2nd argument, we use the $1 placeholder to get the matched string and then add ... after it.

Therefore, in the console log, we get the same result as before.

Lodash truncate Method

Another way to truncate a string easily is to use the Lodash truncate method.

For instance, we can write:

const truncated = _.truncate('Lorem ipsum dolor sit amet, consectetur adipiscing elit.', {
  length: 12
});
console.log(truncated)

to call the truncate method to truncate the string.

The first argument is the string to truncate.

And the 2nd argument is the options for truncating.

We set length to 12 to truncate the string to 12 characters long including the ellipsis.

Therefore, truncated is 'Lorem ips…’ is the value of truncated .

Conclusion

We can use plain JavaScript string methods or Lodash truncate method to truncate a string in JavaScript.

Categories
JavaScript Answers

Why Does Adding Two Numbers in JavaScript Concatenates Them Instead of Calculating the Sum?

Sometimes, we may see that if we use the + operator to add 2 numbers with JavaScript that they’re concatenated instead of being added together.

In this article, we’ll look at why using the + operator will concatenate the 2 numbers instead of adding them together.

One or More of the Operands aren’t Numbers

The reason that adding 2 numbers together in JavaScript is that one or more of the operands that we try to add together may not be numbers.

Therefore, we should make sure that they’re both numbers before trying to add them.

To do this, we can convert to numbers with various functions or operators.

For instance, we can write:

const y = '1'  
const z = '2'  
const x = +y + +z;  
console.log(x)

to use the unary + operator to convert y and z to numbers.

Therefore, x is 2 since we add the numbers 1 and 2 together.

Another way to convert the operands to numbers is to use the Number function.

For instance, we can write:

const y = '1'  
const z = '2'  
const x = Number(y) + Number(z);  
console.log(x)

Number returns the number converted from the argument, so we get the same value for x as the previous example.

Another function we can use to convert non-numbers to numbers is the parseInt function.

It’ll convert non-numbers to integers.

For example, we can write:

const y = '1'  
const z = '2'  
const x = parseInt(y, 10) + parseInt(z, 10);  
console.log(x)

The first argument is the non-number value to convert.

And the 2nd argument is the base of the number to convert the number to.

10 means we convert it to a decimal number.

Conclusion

To make sure that we’re adding 2 values together instead of concatenating them with the JavaScript + operator, we should convert the values to numbers before trying to add them.

Categories
JavaScript Answers

How to Get the Last Element of a Split String Array?

Sometimes, we may want to get the last element of a split string array.

In this article, we’ll look at how to get the last element of a split string array.

Use the Array length Property

We can use the length property of an array and subtract 1 from it to get the last index of the array.

And we can use the split method to split a string into an array of strings given a separator string.

For instance, we can write:

const str = "hello,how,are,you,today?";
const pieces = str.split(/[s,]+/);
const last = pieces[pieces.length - 1]
console.log(last)

We call split with a regex that matches commas to split the string by the commas.

Then we get the last element in the pieces split string array with index pieces.length — 1 .

Therefore, last is 'today?' .

Use the Array.prototype.pop Method

The array instance’s pop method removes the last element of an array in place and returns the removed element.

Therefore, we can use it to get the last item of the split string array.

For example, we can write:

const str = "hello,how,are,you,today?";
const pieces = str.split(/[s,]+/);
const last = pieces.pop()
console.log(last)

And we get the same result as before for last .

Use the Array.prototype.slice Method

The array instance’s slice method lets us get a part of an array given the start and end index.

To get the last element of the array, we can pass in index -1 as the start index to return an array that has the last element of the array.

We don’t need the end index since the default value for the end index is the last index of the array.

Therefore, we can write:

const str = "hello,how,are,you,today?";
const pieces = str.split(/[s,]+/);
const last = pieces.slice(-1)[0]
console.log(last)

We use [0] to get the first element of the array returned by slice .

And so we get the same value for last as before.

Conclusion

We can use various array methods to get the last string in the split string array with JavaScript.

Categories
JavaScript Answers

How to Unescape HTML Entities in JavaScript?

Sometimes, we may want to unescape strings with HTML entities in our web app.

In this article, we’ll look at how to unescape HTML entities in JavaScript.

Unescape HTML Entities with a Text Area

One way to unescape HTML entities is to put our escaped text in a text area.

This will unescape the text, so we can return the unescaped text afterward by getting the text from the text area.

For instance, we can write:

const htmlDecode = (input) => {
  const e = document.createElement('textarea');
  e.innerHTML = input;
  return e.childNodes.length === 0 ? "" : e.childNodes[0].nodeValue;
}

const result = htmlDecode("&lt;img src='myimage.jpg'&gt;");
console.log(result)

We have an htmlDecode function that takes an input string as a parameter.

In the function, we create the textarea element with the document.createElement .

Then we set the innerHTML of it to input .

Then we get the unescaped text by getting the childNodes[0].nodeValue property and return it.

Now when we pass in an escaped string, we’ll get the unescaped version back.

So “&lt;img src=’myimage.jpg’&gt;” becomes "<img src=’myimage.jpg’>" .

Use the DOMParser.prototype.parseFromString Method

Another way to unescape a string is to use the DOMParser.prototype.parseFromString method.

To use it, we pass in the escaped string, and the MIME type of the string to return.

For instance, we can use it by writing:

const htmlDecode = (input) => {
  const doc = new DOMParser().parseFromString(input, "text/html");
  return doc.documentElement.textContent;
}

const result = htmlDecode("&lt;img src='myimage.jpg'&gt;");
console.log(result)

We create a new DOMParser instance.

Then we call parseFromString with the input string and the MIME type string of the string to convert to.

And then get the unescaped string with doc.documentElement.textContent and return it.

Therefore, result would be the same as the previous example.

Unescape HTML Entities with a Div

We can also create a div, set its innerHTML property to the escaped string.

Then we can get the unescaped string from the innerText property.

To do this, we write:

const htmlDecode = (input) => {
  const e = document.createElement('div');
  e.innerHTML = input;
  return e.innerText
}

const result = htmlDecode("&lt;img src='myimage.jpg'&gt;");
console.log(result)

We set e.innerHTML to input .

Then we return e.innerText to return the unescaped text.

And so we get the same result as the previous examples.

Conclusion

There are several ways we can use to unescape strings with HTML entities in JavaScript.