Categories
JavaScript Answers

How to Strip All Non-Numeric Characters from a String in JavaScript?

Stripping all non-numeric characters from a string is something that we do sometimes in our JavaScript apps.

In this article, we’ll look at how to strip all non-numeric characters from a string with JavaScript.

String.prototype.replace

To strip all non-numeric characters from a string in JavaScript, we can use the string replace method to find all non-numeric characters and replace them with empty strings.

For instance, we can write:

const str = 'abc123'
const newStr = str.replace(/D/g, '');
console.log(newStr)

to call replace with a regex to get all non-numeric characters and replace them with an empty string.

D mean non-numeric characters.

And g means we search for all instances of the given pattern in the string.

Therefore, newStr is '123' .

Also, we can use the 0-9 pattern to search for digits. so we can write:

const str = 'abc123'
const newStr = str.replace(/[^0-9]/g, '');
console.log(newStr)

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

To leave decimal points and negative signs in the string, we can do a more precise replacement by writing:

const str = 'abc123.45'
const newStr = str.replace(/[^d.-]/g, '');
console.log(newStr)

^d.- means we search for anything other than digits, decimal points, and the negative sign and replace them all with empty strings.

So newStr is ‘123.45’ .

Conclusion

We can use the string’s replace instance method to strip all non-numeric characters from a string with JavaScript.

Categories
JavaScript Answers

How to Get the Difference Between Two Arrays in JavaScript?

Sometimes we need to get the difference between 2 JavaScript arrays.

The difference is the item in one array that’s not in the other.

In this article, we’ll look at how to get various kinds of differences between 2 arrays in JavaScript.

Intersection

The intersection between 2 arrays is a set of items that are in both arrays.

To get the intersection, we can use the filter method.

We can write:

const arr1 = ['a', 'b'];
const arr2 = ['a', 'b', 'c', 'd'];
const intersection = arr1.filter(x => arr2.includes(x));
console.log(intersection)

to computer the intersection.

We have 2 arrays, arr1 and arr2 .

And we compute the intersection by calling filter on arr1 with a callback that checks whether the item x from arr1 is also included with arr2 .

We can switch arr1 and arr2 in the 3rd line and get the same result.

For instance, we can write:

const arr1 = ['a', 'b'];
const arr2 = ['a', 'b', 'c', 'd'];
const intersection = arr2.filter(x => arr1.includes(x));
console.log(intersection)

In both cases, intersection is [“a”, “b”] .

Difference Between 2 Arrays

The difference between 2 arrays is an array of all the items that are available in one array but not the other.

For instance, if we have arr1 and arr2 like we have above, we can get all the items from arr2 that isn’t in arr1 by writing:

const arr1 = ['a', 'b'];
const arr2 = ['a', 'b', 'c', 'd'];
const intersection = arr2.filter(x => !arr1.includes(x));
console.log(intersection)

All we did is change the filter callback to check whether item x in arr2 is included in arr1 or not.

If they aren’t then we include it in the intersection array.

Therefore, intersection is [“c”, “d”] .

Symmetric Difference Between 2 Arrays

The symmetric difference between 2 arrays is the set of items that are in either array but not both.

To compute the symmetric difference, we can write:

const arr1 = ['a', 'b', 'e'];
const arr2 = ['a', 'b', 'c', 'd'];
const symDiff = [...new Set([...arr1, ...arr2])].filter(x => (!arr1.includes(x) && arr2.includes(x)) || (arr1.includes(x) && !arr2.includes(x)))
console.log(symDiff)

We put all the array items into a set by passing an array with both the entries from arr1 and arr2 in it into the Set constructor.

This will remove any duplicate elements from the combined arrays.

Then we convert the set back to an array with the outer spread operator.

And then we call filter on that with:

(!arr1.includes(x) && arr2.includes(x)) || (arr1.includes(x) && !arr2.includes(x))

returned by the callback to get all the elements that are only in arr1 or only in arr2 .

Therefore, symDiff should be [“e”, “c”, “d”] .

Conclusion

We can compute various kinds of differences between arrays with sets and array methods.

Categories
JavaScript Answers

How to Pass Arguments to the JavaScript setTimeout Function’s Callback?

The setTimeout function lets us run JavaScript code after a delay in milliseconds.

In this article, we’ll look at how we can pass in arguments to the JavaScript setTimeout function.

Call setTimeout with More Argumemts

One way to pass arguments to the setTimeout function’s callback is to pass them in after the 2nd argument of setTimeout .

For instance, we can write:

setTimeout((greeting, name) => {  
  console.log(greeting, name)  
}, 1000, 'hello', 'jane')

We have a callback that takes the greeting and name parameters.

And we have the 'hello' and 'jane' arguments after the 2nd argument.

They’ll get passed into the callback in the same order.

So the console log should log hello jane .

Use the bind Method

The bind method lets us return a function with the arguments we want passed in.

So we can use the function returned by bind as the callback instead.

For instance, we can write:

const greet = (greeting, name) => {  
  console.log(greeting, name)  
}  
setTimeout(greet.bind(undefined, 'hello', 'jane'), 1000)

to call greet with the arguments that we pass into bind with setTimeout .

The 2nd and subsequent arguments of bind are passed into the greet function.

So we get the same result as before.

Call the Function in the Callback

Another way we can pass arguments into the setTimeout callback is to call the function we want in the callback.

For instance, we can write:

const greet = (greeting, name) => {  
  console.log(greeting, name)  
}  
setTimeout(() => {  
  greet('hello', 'jane')  
}, 1000)

Instead of trying to pass the greet function into setTimeout directly, we call greet in the callback with the arguments that we want instead.

This gives us the same results as before.

Conclusion

There’re several ways to pass in arguments to the setTimeout callback.

We can transform the callback with bind , or we can pass in the arguments directly to setTimeout .

Also, we can call the function we want in the callback.

Categories
JavaScript Answers

How to Create a File in Memory for Users to Download on Client Side with JavaScript?

Sometimes, we may want to let users download files that aren’t stored on a server.

The data may only be available on the client-side and we want to let users download time.

In this article, we’ll look at how to create a file in memory for users to download on the client-side with JavaScript.

Setting a Tag’s href Attribute to a Base64 String

We can set an a tag’s href attribute’s value to a base64 string.

This way the data will be downloaded to the user’s computer.

For instance, we can add a text file for the user to download by writing:

<a href="data:application/octet-stream;charset=utf-16le;base64,//5mAG8AbwAgAGIAYQByAAoA">text file</a>

href is set to a base64 string.

It consists of the MIME type, which is application/octet-stream .

And the part after the double slash is the encoded text content.

Create File to Download with JavaScript

We can also create the file to download with JavaScript.

For instance, we can write the following HTML:

<button>
  download
</button>

Then we can create a function to let us download content by writing

const download = (filename, text) => {
  const element = document.createElement('a');
  element.setAttribute('href', `data:text/plain;charset=utf-8,${encodeURIComponent(text)}`);
  element.setAttribute('download', filename);
  element.style.display = 'none';
  document.body.appendChild(element);
  element.click();
  document.body.removeChild(element);
}

const button = document.querySelector('button')
button.addEventListener('click', () => {
  download('file.txt', 'foo bar')
})

In the download function, we get the filename and text parameter values.

Then in the function, we create the a element with createElement .

It’ll be invisible.

Next, we set the href attribute value of it to the content we want to the user to get, which is a base64 string with the encoded text value.

Then we set the download attribute to the filename so the file will be downloaded with the given filename.

Next, we set display style to 'none' so that it’s visible.

And then we append the a element to the body with appendChild .

To download the file, we call click to click on the invisible a element.

And finally, we call removeChild to remove the invisible a element.

Then we get the button with querySelector .

And we call addEventListener on it to add a click listener.

And in the callback, we call download with the filename and content.

Also, we can use createObjectURL to create the base64 string:

const download = (filename, text) => {
  const element = document.createElement('a');
  element.setAttribute('href', window.URL.createObjectURL(new Blob([text], {
    type: 'text/plain'
  })));
  element.setAttribute('download', filename);
  element.style.display = 'none';
  document.body.appendChild(element);
  element.click();
  document.body.removeChild(element);
}

const button = document.querySelector('button')
button.addEventListener('click', () => {
  download('file.txt', 'foo bar')
})

Conclusion

We can use base64 strings with a elements to let users download data that are only available on the client side.

Categories
JavaScript Answers

How to Merge Properties of Two JavaScript Objects Dynamically?

JavaScript objects have dynamic properties.

This means that we can merge the properties of 2 JavaScript objects dynamically.

This is an operation that’s done frequently.

In this article, we’ll look at how to merge properties of 2 JavaScript objects dynamically.

Spread Operator

The spread operator is available to objects since ES2018.

It lets us merge 2 objects’ properties together with ease.

For instance, we can write:

const obj1 = {
  a: 1
}
const obj2 = {
  b: 2
}
const merged = {
  ...obj1,
  ...obj2
};

The spread operator is the 3 dots.

It copies the p[roperies from obj1 and obj2 in the same order that they’re written.

Therefore, merged is {a: 1, b: 2} .

If 2 objects have the same properties, then the value of the last one that’s merged in overwrites the one that’s there previously.

For instance, if we have:

const obj1 = {
  a: 1
}
const obj2 = {
  a: 2
}
const merged = {
  ...obj1,
  ...obj2
};

Then merged is {a: 2} .

Object.assign

The Object.assign method also lets us combine 2 objects together and return one merged object as the result.

For instance, we can write:

const obj1 = {
  a: 1
}
const obj2 = {
  b: 2
}
const merged = Object.assign(obj1, obj2);

Then merged is {a: 1, b: 2} .

The object in the first argument is mutation.

So if we want to return a new object with the properties of 2 objects without changing them, we pass in an empty array as the first argument:

const obj1 = {
  a: 1
}
const obj2 = {
  b: 2
}
const merged = Object.assign({}, obj1, obj2);

Object.assign is available since ES6

for-in Loop

If the 2 ways above aren’t available, then we can use the for-in loop as the last resort.

It’s definitely not recommended since the 2 options above have been available for a few years.

And they’re much simpler and easier to use.

But if we need to use the for-in loop, we write:

const obj1 = {
  a: 1
}
const obj2 = {
  b: 2
}

const merged = {}
for (const prop in obj1) {
  merged[prop] = obj1[prop];
}

for (const prop in obj2) {
  merged[prop] = obj2[prop];
}

We loop through all the properties of obj1 and obj2 with the for-in loop and put all the properties values into the merged object.

prop has the property name.

And so merged is:

{a: 1, b: 2}

Conclusion

We can use the spread operator and Object.assign to merge properties from different objects into one object.