vcapra1
vcapra1

Reputation: 2025

JS: determine amount of occurrences in a string

Is there a way to determine the number of times a letter occurs inside another string?


if not, can you determine the number of times a string is in an array

if you can do it with the array, how can you split 2 words, such as: Hello, World! into an array of 2 words, like this:

["Hello", "World"]

Upvotes: 0

Views: 48

Answers (2)

Matt
Matt

Reputation: 3677

The number of times a letter occurs in a string

This can be found as follows:

"Hello World Hello World!".match(/e/g).length    // Will result in 2

/e/g is a regular expression that matches the letter 'e'. The 'g' stands for "global" and gets all the occurances in a string.

String in an array

This can be found as follows:

var arrayOfStrings = ["Hello", "World", "Hello", "World"],
    wordCount = 0,
    i;

for (i = 0; i < arrayOfStrings.length; i += 1) {    // Remember to optimise length call
    if (arrayOfStrings[i] === "Hello") {
        wordCount += 1;
    } 
}

console.log(wordCount) // This will log 2

Upvotes: 0

Ben McCormick
Ben McCormick

Reputation: 25718

Sure. A simple one liner that comes to mind is

var numOccurrences = str.split("<char>").length -1

where can be replaced with whatever character (or string) you want to test for

That will split the string on each occurrence and then take the length of the resulting array -1. Which will tell you the number of occurrences.

If you want to do it while ignoring upper/lower case, you can use regex

str.match(/<char>/gi).length

Upvotes: 1

Related Questions