Like any kind of apps, there are difficult issues to solve when we write JavaScript apps.
In this article, we’ll look at some solutions to common JavaScript problems.
Replace All Commas in a String
We can replace all commas in a string with the replace
method.
For instance, we can write:
const str = 'foo,bar,baz';
const newStr = str.replace(/,/g, '-');
Then newStr
is “foo-bar-baz”
.
Good Way to Extend Error in JavaScript?
We can extend the Error
class with the extends
keyword.
For instance, we can write:
class SpecialError extends Error {
constructor(message) {
super(message);
this.name = 'special error';
}
}
We created a SpecialError
class which inherits from the Error
class.
We can set our own name
to distinguish it from the Error
instance.
Convert String with Commas to Array
We can convert strings with commas to an array with the split
method.
For instance, we can write;
const string = "1,2,3";
const array = string.split(",");
console.log(array);
We have a string
that we call split
on with a comma to split the string into an array.
Add or Update a Query String Parameter
To add or update a query string parameter, we can create a URLSearchParams
instance with the query string.
Then we can call set
on it with the key and value to set the parameter.
For instance, we can write:
const searchParams = new URLSearchParams(window.location.search)
searchParams.set("foo", "baz");
const newURL = `${window.location.pathname}?${searchParams.toString()}`;
history.pushState(null, '', newURL);
We get the query string in the browser search bar with window.location.search
.
Then we call set
with the key and value of it.
Next, we get the query string by calling toString
on the URLSearchParams
instance.
And we combine the pathname and query string together.
Then we call pushState
to with the new URL to reload the page with the new query string.
Open a URL in a New Window Rather than a Tab
To always open a URL in a new window rather than a tab, we can pass in a 3rd argument to window.open
with the width and height of the window.
For instance, we can write:
window.open(url, '_blank', "height=200,width=200");
The 3rd argument has the specifications of the window.
Check if a Variable is a Number
We can check if a variable is a number by using the isNaN
and isFinite
functions.
For instance, we can write:
!isNaN(parseFloat(num)) && isFinite(num);
We use parseFloat
to try to parse num
to a float.
Then we can check the returned value with isNaN
.
We also pass num
to isFinite
to check that.
If both expressions are true
then we know we got a finite number.
Creating a Text Area with Auto-Resize
To create a text area with auto-resize, we can listen to the input event.
Then we can set the height of the text area in the input event listener to the scrollHeight
plus 12 pixels.
scrollHeight
gets the full height of the text.
To do that we can write:
<textarea></textarea>
to create the text area.
Then we can write:
function resizeTextarea(ev) {
this.style.height = 'auto';
this.style.height = `${this.scrollHeight}px`;
}
const textArea = document.querySelector('textarea');
textArea.addEventListener('keyup', resizeTextarea);
'auto'
resets the height to the original.
Then we set the height to the scrollheight
to make it the height of the text.
Why Shouldn’t we use document.write?
We shouldn’t use document.write
to render HTML on the screen.
It doesn’t work with XHTML.
It’s run after the page finishes loading and overwrites the page.
Also, it runs where it’s encountered.
It’s doesn’t write content like we do with DOM manipulating and can easily create bugs since we’re writing string’s content onto a page.
Therefore, we shouldn’t use document.write
to write content onto the screen.
Check if the URL has a Given String
We can use the indexOf
method on window.location.href
to check if a URL contains a given string.
For instance, we can write:
window.location.href.indexOf("foo") > -1
to check if 'foo'
is in the current page’s URL.
If the returned value is -1, that means it’s not in the URL.
Otherwise, it’s in the URL.
Conclusion
We can use the URLSearchParams
constructor to parse and manipulate query strings.
window.open
can open a new window.
The Error
constructor can be extended with a child class.