Categories
JavaScript Answers

How to Replace a Character at a Particular Index in JavaScript?

Sometimes, we need to replace a character at a particular index in our JavaScript strings.

In this article, we’ll look at how to replace a character at a particular index with JavaScript.

Use the String.prototype.substr Method

We can extract substrings from a string with the substr method.

This will help us with the replacement since we can extract the substrings from index 0 to the index of the character we want to replace.

And we can extract the string from the index to the end of the string.

Then we can add the replacement between the 2 substrings.

For instance, we can write:

const replaceAt = (str, index, replacement) => {
  return str.substr(0, index) + replacement + str.substr(index + 1);
}

const str = 'a b c'
const newStr = replaceAt(str, 2, 'foo')
console.log(newStr)

We create the replaceAt function which takes the str string that we want to the replacement with.

The index of the character that we want to replace.

And replacement is the replacement string.

Then we return the first substring concatenated with the replacement concatenated with the 2nd substring.

So when we pass in the arguments to it, we get newStr , which is:

'a foo c'

The substr and substring method are the same so we can write:

const replaceAt = (str, index, replacement) => {
  return str.substring(0, index) + replacement + str.substring(index + 1);
}

const str = 'a b c'
const newStr = replaceAt(str, 2, 'foo')
console.log(newStr)

We can use this to replace any character with another substring of any length.

String.prototype.split and String.prototype.join

We can also use the split and join methods to split and join a string together.

For instance, we can write:

let str = 'a b c'
str = str.split('');
str[2] = 'd';
str = str.join('');
console.log(str)

We call split with an empty string to split the string into an array of characters.

Then we assign the character of a string with the given index with a new character.

And then we join the string back together with the join method and an empty string as an argument.

Therefore, str should be 'a d c’ .

This is handy for replacing one character with another.

Conclusion

To replace a character with another substring, we can split the string into substrings.

Then we can join them back together with a replacement.

We can also split a string into an array of characters, assign the character at the position to another character.

Then we can join the string back together.

Categories
JavaScript Answers

How to Watch the JavaScript Window Resize Event?

We can watch window resize events with JavaScript to detect screen size changes of any kind.

In this article, we’ll look at how to watch the JavaScript window resize event to detect window resizes.

Assign an Event Handler to the window.onresize Property

One way to add an event handler for the window resize event is to assign an event handler function to the window.onresize property.

For instance, we can write:

window.onresize = (event) => {  
  console.log(event)  
};

to assign a function to window.onresize .

The event parameter has the event object, which is the data emitted with the window resize event.

Call window.addEventListener to Attach an Resize Event Handler

We can also call the window.addEventListener method to attach an event listener for window .

To listen to the resize event, we pass in 'resize' as the first argument.

And the 2nd argument is the event handler for the resize event.

For instance, we can write:

window.addEventListener('resize', (event) => {  
  console.log(event)  
});

The event parameter is the same one as we assigned to the onresize method in the example before.

ResizeObserver

A more modern way to watch for resizing of an element is to use the ResizeObserver constructor.

It lets us create an object with tyhe observe method that takes the element we want to watch the resizing of.

For instance, we can write:

const ro = new ResizeObserver(entries => {  
  for (const entry of entries) {  
    const cr = entry.contentRect;  
    const {  
      width,  
      height,  
      top,  
      left  
    } = cr  
    console.log(entry.target);  
    console.log(width, height, top, left)  
  }  
});  
ro.observe(document.querySelector('html'));

We invoke the ResizeObserver constructor with a function that loops through the entries whyich has the items we’re watching.

And in the loop body, we get the dimensions from the entry.contentRect property.

width and height have the width and height of the element.

top and left have the x and y coordinates of the top left corner respectively.

entry.target has the element we’re watching.

Then we call ro.observe with the element that we’re watching.

If we want to watch the browser window’s resizing, then we can watch the html element.

We can select it with document.querySelector .

Conclusion

We can listen to resize events by assigning a resize event listener to the window object.

Or we can use the ResizeObserver constructor to create an object that lets us watch an element for resizing.

Categories
JavaScript Answers

How to Get the First Character of a JavaScript String?

Sometimes, we need to get the first character of a JavaScript string in our code.

In this article, we’ll look at how to get the first character of a JavaScript string.

String.prototype.charAt

The chartAt method that comes with JavaScript strings lets us get a character from a string by its index.

To get the first character, we pass in 0 to the method.

For instance, we can write:

const first = 'abc'.charAt(0)
console.log(first)

Therefore, first is 'a' .

String.prototype.substring

The substring method lets us get a substring from a string given the start and end index.

The character at the starting index is included.

But the character at the ending index isn’t.

So we can write:

const first = 'abc'.substring(0, 1)
console.log(first)

And we get the same result.

String.prototype.slice

Like the substring method, the slice method also lets us get a substring with the start and end indexes.

Like substring, the character at the starting index is included.

But the character at the ending index isn’t.

For instance, we can write:

const first = 'abc'.slice(0, 1)
console.log(first)

And we get the same results as the other examples.

Square Brackets

We can pass in the index of the first character into square brackets as we do with charAt .

For example, we can write:

const first = 'abc'[0]
console.log(first)

Then we get the same result as with charAt .

Conclusion

There are several ways we can get the first character of a string with JavaScript.

We can do it either with square brackets or string methods.

Categories
JavaScript Answers

How to Repeat a String in JavaScript a Number of Times?

Sometimes, we’ve to create a string that’s generated by repeating a string a number of times in our JavaScript code.

In this article, we’ll look at how to repeat string in JavaScript easily.

String.prototype.repeat

The repeat method that comes with JavaScript strings lets us create a string that’s created by repeating the string that it’s called on.

For instance, we can write:

const str = "b".repeat(10)
console.log(str);

We call repeat with number of times we want to repeat 'b' for.

So str is ‘bbbbbbbbbb’ .

Array Constructor

We can use the Array constructor to create an array with the given number of empty slots.

And we can call join on it with the striogn we want to repeat it.

For instance, we can write:

const str = Array(11).join("b")
console.log(str);

The length of the array is 1 bigger than the number of times we want to repeat the string.

This is because join puts the string in between the array entries.

So we get the same result as before.

Use a Loop

We can use a loop to create the repeated string.

For instance, we can write:

let word = ''
for (let times = 0; times < 10; times++) {
  word += 'b'
}
console.log(word)

We create a for loop that runs for 10 iterations.

And in the loop body, we append the string we want into the word string.

And so word is 'bbbbbbbbbb’ like we have before.

Lodash repeat Method

Since Lodash 3.0.0, it comes with the repeat method that lets us return a string that’s the repeat of a given substring by the given number of times.

For instance, we can write:

const word = _.repeat('b', 10)
console.log(word)

Then word is 'bbbbbbbbbb’ since we specified that we want to repeat 'b' for 10 times.

Conclusion

We can repeat a string with the Lodash repeat method or the native string repeat method.

Also, we can use a loop to append a string.

Categories
JavaScript Answers

How to Create a Zero-Filled JavaScript Array?

We’ve to create a JavaScript array filled with all zeroes in our code.

In this article, we’ll look at how to create a zero-filed JavaScript array.

Array.prototype.fill

We can use the fill array method to fill all the entries of an array with the values we want.

For instance, we can write:

const arr = new Array(10).fill(0);  
console.log(arr);

The Array constructor takes the length of an array if we only pass one argument into it.

fill takes the value we want to fill the array with.

Then arr is [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] .

fill is available since ES6.

The apply and map Methods

We can also use the Array.apply method to create an empty array that we can use the map method with.

Then we pass in a callback that returns the value we want into the map method.

For instance, we can write:

const arr = Array.apply(undefined, Array(10)).map(() => 0);  
console.log(arr);

We call apply with Array(10) to create an array with 10 slots that we can fill with map .

Then in map , we just pass in a callback that returns 0 to fill all the entries with zeroes.

So we get the same result as the previous example.

Array.from

The Array.from method is an array static method that lets us return an array derived from another array.

So we can use it to map the values from one array to another, including an empty array.

For instance, we can write:

const arr = Array.from(Array(10), () => 0)  
console.log(arr);

We call Array.from with Array(10) to let us map the empty array with 10 slots to an array with stuff inside.

The 2nd argument is a callback that returns 0 so we fill all the entries with zeroes.

Therefore, we get the same result as before.

Another way to use Array.from is to pass in an object with the length property set to the array length we want.

To do this, we write:

const arr = Array.from({  
  length: 10  
}, () => 0)  
console.log(arr);

And we get the same result as before.

Conclusion

We can create a zero-filled array with JavaScript by using the fill method or the Array.from method.

Also, we can use the Array constructor to create an array.