Categories
JavaScript Answers

How to Extract the Base URL from a String in JavaScript?

Sometimes, we want to extract the base URL from a string with JavaScript.

In this article, we’ll look at ways to extract the base URL from a string with JavaScript.

Create an Anchor Element and Get the Base URL Parts From the Created Element

We can create an anchor element and get the base URL parts from the created element.

For instance, we can write:

const a = document.createElement("a");
a.href = "http://www.example.com/article/2020/09/14/this-is-an-article/";
const baseUrl = `${a.protocol}//${a.hostname}`
console.log(baseUrl)

We create the a element with document.createElement .

Then we set the href of it to the URL we want to extract the base URL from.

Then we can get the baseURL by combining the protocol and hostname properties.

As a result, we see that baseURL is ‘http://www.example.com’ .

Create a URL Object and Get the Base URL Parts From the Created Element

Another way to get the base URL from a URL is to create an URL instance and extract the base URL parts from the object.

For instance, we can write:

const url = new URL("http://www.example.com/article/2020/09/14/this-is-an-article/")
const baseUrl = `${url.protocol}//${url.hostname}`
console.log(baseUrl)

We pass in the full URL as an argument of the URL constructor.

Then we can get the base URL by combining the protocol and hostname as we did before.

And so baseURL should be the same as the previous example.

Conclusion

We can extract the base URL from a string with JavaScript by creating an anchor element or using the URL constructor.

Categories
JavaScript Answers

How to Output Numbers With Leading Zeros in JavaScript?

Sometimes, we want to output numbers with leading zeroes in our JavaScript programs.

In this article, we’ll look at how to create numbers with leading zeroes with JavaScript.

String.prototype.padStart

The JavaScript string’s padStart method lets us add characters we want to a string until it reaches a given length.

For instance, we can write:

const padded = (123).toString().padStart(5, '0')
console.log(padded)

We call toString on the number to convert it to a string.

Then we call padStart with 5 to pad the string to length 5.

And we pass in '0' to pad the number with leading 0’s.

Therefore, padded is '00123' .

Write Our Own Code

We can also write our own code to pad a number string with leading zeroes.

For instance, we can write:

const zeroPad = (num, places) => {
  const numZeroes = places - num.toString().length + 1;
  if (numZeroes > 0) {
    return Array(+numZeroes).join("0") + num;
  }
  return num
}

console.log(zeroPad(5, 2))
console.log(zeroPad(5, 4))
console.log(zeroPad(5, 6))

We create the zeroPad function that takes the num and places parameters.

num has the number we want to pad with leading zeroes.

places is the number of decimal places that we want to pad to.

In the function, we compute the numZeroes variable, which is the number of leading zeroes we want to add to make the string the length set by places .

We compute that by substracting places with num.toString().length plus 1.

This subtracts the final number of places with the length of the number string plus 1.

We add 1 so that we create the correct sized array since we want to add zeroes in between the array entries with join .

Then if numZeroes is bigger than 0, we return a string with leading zeroes by creating an array, then calling join with 0 to create the zero string, and then concatenating that with the num value.

Otherwise, we return num itself.

So the console log should log:

05
0005
000005

Conclusion

We can pad our JavaScript nuinmber strings with leading zeroes with the padStart method or write our own code to do so.

Categories
JavaScript Answers

How to Let Users Download JavaScript Array Data as a CSV on Client-Side?

Sometimes, we may want to let users download a nested array with data as a CSV text file.

In this article, we’ll look at how to let users download a JavaScript array’s data as a CSV on the client-side.

Using the window.open Method

We can use the window.open method to open a URL encoded string to let users download that to their computer.

For instance, we can write:

const rows = [
  ["name1", "new york", "abc"],
  ["name2", "san francisco", "def"]
];

let csvContent = "data:text/csv;charset=utf-8,";

for (const rowArray of rows) {
  const row = rowArray.join(",");
  csvContent += `${row}rn`;
}
const encodedUri = encodeURI(csvContent);
window.open(encodedUri);

We have the rows nested array that we want to convert to a CSV string and let users download it.

To do the conversion, we first define the beginning of the csvContent string which specifies the MIME type and the character set.

Then we loop through the rows entries, join each row’s entries and append them to the csvContent string with newline characters.

Then we call encodeURI with the csvContent string to encode it to a URL encoded string.

And finally, we can download the string as a file with window.open .

We can also shorten the for-of with the map method:

const rows = [
  ["name1", "new york", "abc"],
  ["name2", "san francisco", "def"]
];

const csvContent = `data:text/csv;charset=utf-8,${rows
  .map((e) => e.join(","))
  .join("n")}`;

const encodedUri = encodeURI(csvContent);
window.open(encodedUri);

We just call map on rows to map each row to a comma-separated string with join .

Then we call join on the mapped strings.

Download the file this way doesn’t let us set the file name.

To let us set the file name, we can create an invisible link and click on it programmatically.

To do that, we weiter:

const rows = [
  ["name1", "new york", "abc"],
  ["name2", "san francisco", "def"]
];
const csvContent = `data:text/csv;charset=utf-8,${rows
  .map((e) => e.join(","))
  .join("n")}`;
const encodedUri = encodeURI(csvContent);
const link = document.createElement("a");
link.setAttribute("href", encodedUri);
link.setAttribute("download", "data.csv");
document.body.appendChild(link);
link.click()

We call createElement to create an a element.

Then we set the href to the encodedUri .

And then we set the download attribute to the file name with setAttribute .

Next, we call appendChild with the link to attach it to the body.

And then we call click on it to click it to start the download.

Save the Data as a Blob

We can save the data as a blob by rewriting the example above.

For instance, we can write:

const rows = [
  ["name1", "new york", "abc"],
  ["name2", "san francisco", "def"]
];
const csvContent = rows
  .map((e) => e.join(","))
  .join("n");
const blob = new Blob([csvContent], {
  type: 'text/csv;charset=utf-8;'
});
const url = URL.createObjectURL(blob);
const link = document.createElement("a");
link.setAttribute("href", url);
link.setAttribute("download", "data.csv");
document.body.appendChild(link);
link.click()
URL.revokeObjectURL(link.href)

We have the csvContent string that only has the CSV string content.

Then we create a blob from it with the Blob constructor.

In the 2nd argument of it, we set the type to the data type of the blob.

Next, we call URL.createObjectURL to create an encoded URL that we can download.

And we create the link element the same way as before, but with url created from URL.createObjectURL instead.

Also, we’ve to call URL.revokeObjectURL to free up resources after the download is done.

Conclusion

We can let generate CSVs from nested arrays on client-side and let users download them with some JavaScript code.

Categories
JavaScript Answers

How Create an Associative Array or Hash in JavaScript?

In many programming languages, associative arrays let us store key-value pairs in our JavaScript app.

In this article, we’ll look at how to create associative arrays or a hash with JavaScript.

Create Associate Arrays with Objects

One way to create associative arrays is with JavaScript objects.

This is because we can remove JavaScript object properties dynamically.

The property name is the key and the value is the value.

For instance, we can write:

const dictionary = {}
dictionary.a = 1
dictionary.b = 2
console.log(dictionary)

to create the dictionary object with properties a and b .

dictionary is {a: 1, b: 2} .

We can also put property names in square brackets as strings.

For instance, we can write:

const dictionary = {}
dictionary['a'] = 1
dictionary['b'] = 2
console.log(dictionary)

This lets us add property names dynamically in our code.

Then to iterate through the object, we can use the Object.keys , Object.values or Object.entries methods.

Object.keys returns an array of keys of an object.

Object.values returns an array of values of an object.

Object.entries returns an array of array of key-value pairs of an object.

For instance, we can write:

const dictionary = {}
dictionary.a = 1
dictionary.b = 2

for (const key of Object.keys(dictionary)) {
  console.log(key, dictionary[key])
}

Then we get:

a 1
b 2

from the console log.

key has the key that’s being iterated through with the for-of loop.

We can loop through the values with Object.values :

const dictionary = {}
dictionary.a = 1
dictionary.b = 2

for (const value of Object.values(dictionary)) {
  console.log(value)
}

So we get:

1
2

from the console log.

And we can loop through the key-value pairs with Object.entries :

const dictionary = {}
dictionary.a = 1
dictionary.b = 2

for (const [key, value] of Object.entries(dictionary)) {
  console.log(key, value)
}

We destructure the key and value from the array being iterated through to get the key and value.

And so we get:

a 1
b 2

Since Object.keys , Object.values or Object.entries methods return arrays, we can get the length with the length property of what they return.

Maps

ES6 comes with the Map constructor to let us create associative arrays or hashes.

For instance, we can use it by writing:

const map = new Map()
map.set('a', 1)
map.set('b', 2)

We call the set method with the key and value respectively to add the entry.

Then we can iterate through it with the for-of loop since it’s an iterable object:

for (const [key, value] of map) {
  console.log(key, value)
}

We can use the get method with the key to getting the value for the given key:

const map = new Map()
map.set('a', 1)
map.set('b', 2)
console.log(map.get('a'))

We pass in 'a' to return 1, which is what we have on the map.

To get the size, we use the size property:

const map = new Map()
map.set('a', 1)
map.set('b', 2)
console.log(map.size)

And the console log should show 2.

Conclusion

We can create an associative array or hash with JavaScript objects with maps.

Categories
JavaScript Answers

How to Set the Value of an Input Field with JavaScript?

One way to set the value of an input field with JavaScript is to set the value property of the input element.

For instance, we can write the following HTML:

<input id='mytext'>

Then we can set the value property of the input by writing:

document.getElementById("mytext").value = "My value";

Call the setAttribute Method

Also, we can call the setAttribute method to set the value attribute of the input element.

For instance, we can write:

document.getElementById("mytext").setAttribute('value', 'My value');

We call setAttribute with the attribute name and value to set the value attribute to 'My value' .

Setting the value Property of an Input in a Form

We can also get the input element by using the document.forms object with the name attribute value of the form and the name attribute value of the input element.

For example, we can write the following HTML:

<form name='myForm'>
  <input type='text' name='name' value=''>
</form>

Then we can use it by writing:

document.forms.myForm.name.value = "New value";

The form name value comes first.

Then the name value of the input element comes after it.

document.querySelector

We can use the document.querySelector method to select the input.

For instance, we can write the following HTML:

<input type='text' name='name' value=''>

Then we can write:

document.querySelector('input[name="name"]').value = "New value";

to get the element with querySelector .

We select the input with the name attribute by putting the name key with its value in the square brackets.

Conclusion

We can set the value of an input field with JavaScript by selecting the element.

Then we can set the value attribute by setting the value property or calling setAttribute .