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.

Categories
JavaScript Answers

How to Count the Number of Substring Occurrences in a JavaScript String?

Sometimes, we’ve to count the number of occurrences of a substring in our JavaScript strings.

In this article, we’ll look at how to count the number of substring occurrences in a JavaScript string.

String.prototype.match

The string match method lets us find the substrings with the given regex pattern in the string it’s called on.

Therefore, we can use it to find the number of substring occurrences in a JavaScript string.

To use it, we write:

const str = "This is a string.";
const count = [...(str.match(/is/g) || [])].length;
console.log(count);

We have the str string.

And we call match on it with the substring we’re looking for and the g flag to look for all instances of the substring in the string.

If there’re no matches, it returns undefined , so we’ve to add || [] to return an empty array in that case.

Then we get the length of the array to get the number of occurences.

So count is 2 since there’re 2 instances of 'is' in the string.

String.prototype.split

We can use the split method to split a string by its separator.

So we can use split to split the string by the substring we’re looking for and subtract that by 1 to get the number of instances of a substring.

To do this, we write:

const str = "This is a string.";
const count = str.split('is').length - 1;
console.log(count);

We call split with 'is' to split the str string with'is' as the separator.

Then we’ve to minus 1 from the returned length to get the right result.

Conclusion

To count the number of instances of a substring in a string, we can either split the string or search for it using a regex.

Categories
JavaScript Answers

How to Duplicate an Array in JavaScript?

Duplicating an array is something that we’ve to do a lot in our JavaScript apps.

In this article, we’ll look at how we can duplicate arrays in JavaScript.

Loops

One way to duplicate a JavaScript array is to use a loop.

For instance, we can use a for-of loop by writing:

const arr = [1, 2, 3]
const clone = []

for (const a of arr) {
  clone.push(a)
}
console.log(clone)

We loop through arr with a for-of loop and call push on clone to add the items into clone .

And so clone should have the same entries as arr .

We can also use a while loop to loop through the array.

For example, we write:

const arr = [1, 2, 3]
const clone = []

let i = 0;
while (i < arr.length) {
  clone.push(arr[i])
  i++
}
console.log(clone)

We get the item by its index with the square brackets and do the same push operator.

Then we increment the i value to move to the next element in the next iteration.

Also, we can use a plain for loop to do the same thing:

const arr = [1, 2, 3]
const clone = []

for (let i = 0; i < arr.length; i++) {
  clone.push(arr[i])
}
console.log(clone)

We put the index changing logic all in the parentheses.

Array.prototype.slice

The slice method returns a clone of the array we’re calling it on if there’re no arguments passed in.

For instance, we can write:

const arr = [1, 2, 3]
const clone = arr.slice()
console.log(clone)

And we get the same result as before.

Array.from

The Array.from method is a static array method that lets us create an array from another array.

Therefore, we can use it to create a clone of the array.

Its first argument is an array or an array-like object we want to create the derived array from.

And the 2nd argument is a function that lets us map the values of the object or array in the first argument and map them to different values.

For example, we can write:

const arr = [1, 2, 3]
const clone = Array.from(arr, a => a)
console.log(clone)

We call Array.from with the arr array.

And the function just returns the value as is.

So we get the same result as in the previous example.

Array.prototype.concat

The concat array instance method also returns an array by combining the array that it’s called with the one that we pass into the argument.

So to use it to clone an array, we can write:

const arr = [1, 2, 3]
const clone = arr.concat([])
console.log(clone)

or:

const arr = [1, 2, 3]
const clone = [].concat(arr)
console.log(clone)

The order doesn’t matter since we only have arr and an empty array.

Either way, we get a clone of arr returned.

Spread Operator

The spread operator also lets us duplicate an array.

For instance, we can write:

const arr = [1, 2, 3]
const clone = [...arr]
console.log(clone)

to clone arr with the spread operator.

So we get the same result as in the previous examples.

Array.prototype.map

The map method lets us return an array that has the values mapped from the original array.

To return a clone of the original array, we just pass in a callback that returns the values being iterated through as-is.

For instance, we can write:

const arr = [1, 2, 3]
const clone = arr.map(a => a)
console.log(clone)

to call map with a call that returns the value being iterated through as-is.

And we get the same result as before.

Conclusion

There’re many ways to clone an array with JavaScript.

The easiest way would be to use the spread operator.

It’s also very fast.