0

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"]

2 Answers 2

1

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
0

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
3
  • Did you actually try this? I got TypeError: Object Hello World Hello World! has no method 'matched' when I ran it in the console. I think you want match Mar 12, 2013 at 23:24
  • A typo—that is what comes of making your code more terse in the editor. Thanks for pointing it out.
    – Matt
    Mar 12, 2013 at 23:30
  • Be careful, if no matches are found, match returns null. So 'abc'.match('e').length throws an error. Test the result before using it.
    – RobG
    Mar 13, 2013 at 0:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.