Categories
JavaScript Answers

How to Replace Text Inside a div Element with JavaScript?

Sometimes, we want to replace text inside a div element with JavaScript.

In this article, we’ll look at ways to replace text inside a div element with JavaScript.

Set the innerHTML Property of an Element

One way to replace the text inside a div element with JavaScript is to set the innerHTML property of an element to a different value.

If we have the following HTML:

<div>  
  hello world  
</div>

Then we can write:

const div = document.querySelector('div')  
div.innerHTML = "My new text!";

to select the div with querySelector .

And then we can set the innerHTML to a new string.

Set the textContent Property of an Element

Another way to replace the text inside a div element with JavaScript is to set the textContent property of an element to a different value.

If we have the following HTML:

<div>  
  hello world  
</div>

Then we can write:

const div = document.querySelector('div')  
div.textContent = "My new text!";

to select the div with querySelector .

And then we can set the textContent to a new string.

Then we get the same result as before.

Set the innerHTML Property of an Element to an Empty String and Insert a new Child Text Node to the Element

Another way to replace the text in a div is to set the innerHTML property to an empty string.

Then we can add a new text node and insert it into the div.

If we have the following HTML:

<div>  
  hello world  
</div>

Then we can write:

const div = document.querySelector('div')  
div.innerHTML = '';  
div.appendChild(document.createTextNode("My new text!"));

to set innerHTML to an empty string.

Then we call document.createTextNode to create a new text node with the text in the argument.

And then we call appendChild to insert the text node to the div.

Conclusion

There are various ways we can use to replace text in a div element with new text in JavaScript.

Categories
JavaScript Answers

How to Create a String of Variable Length Filled with a Repeated Character with JavaScript?

Sometimes, we want to create a string of variable length filled with a repeated character in JavaScript.

In this article, we’ll look at ways to create such strings with JavaScript.

Using the Array Constructor and the Arra.prototype.join Method

We can create an array with the Array constructor.

Then we can call join to join the array entries into a string with the given character as the separator.

For instance, we can write:

const len = 10  
const character = 'a'  
const str = new Array(len + 1).join(character);  
console.log(str)

We create an Array with length len + 1 .

Then we call join with the character that we want to repeat.

Therefore, str is 'aaaaaaaaaa’ .

Use the String.prototype.repeat Method

Another way to create a string of variable length with a repeated character is to use the string’s repeat method.

For instance, we can write:

const len = 10  
const character = 'a'  
const str = character.repeat(len);  
console.log(str)

Then we get the same result as before.

Use a for Loop

We can also use a for loop to concatenate the same character to a string until it reaches the given length.

To do this, we write:

const len = 10  
const character = 'a'  
let str = ''  
for (let i = 1; i <= len; i++) {  
  str += character;  
}  
console.log(str)

We have a for loop that starts with index variable 1 and stops when it reaches len .

In the loop body, we concatenate the character to str .

And so we get the same result as before.

Conclusion

We can create a string that has a variable length with content consisting of a repeated character by using array methods, string methods, or loops.

Categories
JavaScript Answers

How to Get the First Day of the Week from the Current Date with JavaScript?

Sometimes, we want to get the first day of the week from the current date with JavaScript.

In this article, we’ll look at how to get the first date of the week from the current date with JavaScript.

Using Native Date Methods

We can use various date methods to get the first day of the week from the current date.

To do this, we can write:

const getMonday = (d) => {
  const dt = new Date(d);
  const day = dt.getDay()
  const diff = dt.getDate() - day + (day === 0 ? -6 : 1);
  return new Date(dt.setDate(diff));
}

console.log(getMonday(new Date(2021, 1, 20)));

We create the getMonday function takes the d date parameter.

In the function, create a Date instance with the Date constructor.

Then we call getDay to get the day of the week.

It returns 0 for Sunday, 1 for Monday, and so on up to 6 for Saturday.

Then we get the difference between the current date of the week and the Monday of the same week by subtracting the day and then add -6 back if day is 0 and 1 otherwise.

And then we use the Date constructor again by call setDate on dt with diff to set the day to the Monday of the same week.

Therefore, the console log should log:

Mon Feb 15 2021 00:00:00 GMT-0800 (Pacific Standard Time)

as a result.

Conclusion

We can get the Monday of the same week of the given date by getting the day of the week.

Then we subtract the date by the day of the week then add back the number of days to reach the Monday of the same week of the date.

Categories
JavaScript Answers

How to Get JSON Data from a URL in JavaScript?

On many occasions, we want to get JSON data from a URL with JavaScript.

In this article, we’ll look at how to get JSON data from a URL with JavaScript.

Use the Fetch API

The Fetch API lets us make HTTP requests easily within the browser.

It’s promise-based and we can use it to get JSON data easily.

This means we can make multiple requests sequentially easily.

For instance, we can write:

fetch('https://yesno.wtf/api')  
  .then(res => res.json())  
  .then((out) => {  
    console.log(out);  
  })  
  .catch(err => {  
    throw err  
  });

to make a GET request to the URL we pass into fetch .

Then we can res.json in the then callback to convert the response to a JSON object and return a promise with that.

Next, we get the result from the parameter from the 2nd promise callback.

And so we get something like:

{answer: "yes", forced: false, image: "https://yesno.wtf/assets/yes/11-a23cbde4ae018bbda812d2d8b2b8fc6c.gif"}

for out .

We can also use the async and await syntax to make this shorter.

The catch method lets us catch any request errors that arise.

For instance, we can write:

(async () => {  
  try {  
    const res = await fetch('https://yesno.wtf/api')  
    const out = await res.json()  
    console.log(out);  
  } catch (err) {  
    throw err  
  }  
})()

We replaced the then callbacks with await .

And we replaced the catch method with the catch block.

Conclusion

We can use the Fetch API to get JSON data from a URL easily.

It’s a promised-based API which makes making multiple requests sequentially easy.

Categories
JavaScript Answers

How to Get the Closest Number to a Number Out of a JavaScript Array?

Sometimes, we may want to get the closest number to a given number out of a JavaScript array.

In this article, we’ll look at how to get the closest number to a number out of a JavaScript array.

Using the Array.prototype.reduce Method

One way to get the closest number to a number out of a JavaScript array is to use the JavaScript array’s reduce method.

To use it, we write:

const arr = [2, 42, 82, 122, 162, 202, 242, 282, 322, 362]
const goal = 100
const closest = arr.reduce((prev, curr) => {
  return (Math.abs(curr - goal) < Math.abs(prev - goal) ? curr : prev);
});
console.log(closest)

We have the arr array that has a bunch of numbers.

goal is the number that we want to find the closest number in arr from.

We then pass in the callback into the reduce method that compares the absolute value of the difference between curr — goal and prev-goal .

prev is the previously closest number to goal .

And curr is the current number that’s being iterated through.

If curr is closer to goal that prev in absolute value, then we return curr .

Otherwise, we return goal .

Therefore, closest is 82.

Use the Array.prototype.map Method

Another way to find the closest number to a given number is to map all the array entries to the absolute difference between the number in the array and the goal number.

Then we can use Math.min to find the minimum difference between the numbers.

For instance, we can write:

const arr = [2, 42, 82, 122, 162, 202, 242, 282, 322, 362]
const goal = 100
const indexArr = arr.map((num) => {
  return Math.abs(num - goal)
})
const min = Math.min(...indexArr)
const closest = arr[indexArr.indexOf(min)]
console.log(closest)

We call map with a callback that returns the absolute difference between num and goal .

Then we find the minimum of the differences with Math.min .

And then we get the index of the number with the lowest absolute difference with indexOf and pass that into arr to get the number that’s closest to goal .

So we get the same result as the previous example.

Conclusion

We can use JavaScript array and math methods to get the number that’s closest to the given number in an array with JavaScript.