This question already has answers here:
Counting frequency of characters in a string using JavaScript [duplicate]
(21 answers)
Closed 7 years ago.
Can anyone help me to get the count of repeated characters in a given string in javascript.
For example,
"abccdef" -> 1 (Only "c" repeated)
"Indivisibilities" -> 2 ("i" and "s" repeated)
Thank You
You can use like this
function getFrequency(string) {
var freq = {};
for (var i=0; i<string.length;i++) {
var character = string.charAt(i);
if (freq[character]) {
freq[character]++;
} else {
freq[character] = 1;
}
}
return freq;
};
getFrequency('Indivisibilities');
This is an interesting problem. What we can do is turn the string to lower case using String.toLowerCase, and then split on "", so we get an array of characters.
We will then sort it with Array.sort. After it has been sorted, we will join it using Array.join.
We can then make use of the regex /(.)\1+/g which essentially means match a letter and subsequent letters if it's the same.
When we use String.match with the stated regex, we will get an Array, whose length is the answer. Also used some try...catch to return 0 in case match returns null and results in TypeError.
function howManyRepeated(str){
try{ return str.toLowerCase().split("").sort().join("").match(/(.)\1+/g).length; }
catch(e){ return 0; } // if TypeError
}
console.log(howManyRepeated("Indivisibilities")); // 2
Related
This question already has answers here:
Difference between codePointAt and charCodeAt
(3 answers)
Closed 2 years ago.
Getting the first character in a string is fairly straightforward.
const str = 'abc'
str[0] // 'a'
However, when javascript sees a unicode string, it will return the first byte of a multi-byte unicode character.
const strUnicode = '💖hi'
strUnicode[0] // '�'
Is it possible to return the first complete unicode character?
const strUnicode = '💖hi'
f(strUnicode) // '💖'
Issue is that symbols are 16-bit characters. So it takes 2 positions in a character array.
Idea:
Loop over string and validate if current character is a symbol or not.
If symbol, take character at i and i+1. Increment i to skip the processed character
If not, just pick one character
function getCharacters(str) {
const parts = []
for(let i = 0; i< str.length; i++) {
if (str.charCodeAt( i ) > 255) {
parts.push(str.substr(i, 2))
i++
} else {
parts.push(str[i])
}
}
return parts
}
const strUnicode = '💖hi'
console.log( getCharacters(strUnicode) )
This question already has answers here:
Wildcard string comparison in Javascript
(10 answers)
Closed 4 years ago.
I want to test if any string in an array matchs with a particular string. However, the strings in array may contain the asterisks pattern.
var toTest = ["foo_*", "*foo_1", "foo_1*", "bar", "*foo"];
var toMatch = "foo_1";
For this sample, the result will be true because foo_*, *foo_1 and foo_1* will match with foo_1, but bar and *foo won't.
I have tried to use split function with lodash _.some but it seems overcomplicated and I can't make it works consistently.
function isMatching() {
return _.some(toTest , function(a) {
return _.some(a.split("*"), function(part1, idx1) {
return (part1.length && _.some(toMatch.split(part1), function(part2, idx2) {
return (part2.length && idx1 == idx2);
}));
});
});
}
To achieve expected result, use below option of using filter, indexOf and replace
var toTest = ["foo_*", "*foo_1", "foo_1*", "bar", "*_foo"];
var toMatch = "foo_1";
console.log(toTest.filter(v => toMatch.indexOf(v.replace('*', '')) !== -1))
I was solving the Coderbyte Challenge - Questions Marks
When I run my code in the browser it all works fine, however, once I run it on the coderbyte website it throws an error.
The Challenge is:
Have the function QuestionsMarks(str) take the str string parameter,
which will contain single digit numbers, letters, and question marks,
and check if there are exactly 3 question marks between every pair of
two numbers that add up to 10. If so, then your program should return
the string true, otherwise it should return the string false. If there
aren't any two numbers that add up to 10 in the string, then your
program should return false as well.
For example: if str is "arrb6???4xxbl5???eee5" then your program
should return true because there are exactly 3 question marks between
6 and 4, and 3 question marks between 5 and 5 at the end of the
string.
Use the Parameter Testing feature in the box below to test your code
with different arguments.
Test Cases Are:
"arrb6???4xxbl5???eee5" true
"aa6?9" false
"acc?7??sss?3rr1??????5" true
My solution to this was to use RegExp to solve the challenge. the code below works well when I run it in the Browser, however, Coderbyte console throws an error every time:
/tmp/009904362/main.js:11 clean = clean.match(/d(???)d/gi); ^SyntaxError: Invalid regular expression: /d(???)d/
Here is my code -
function QuestionsMarks(str) {
//create a "clean" array containing only the numbers and question marks from str
var result;
let clean = str.match(/[0-9?]/g);
// join() the array back in to the string
clean = clean.join("");
// use match() to return an array of pairs that match the pattern d???d
clean = clean.match(/d(\?\?\?)d/gi);
//create a function sumCheck() that converts first and last char of every array string to Number and checks if the sum of digits is 10
//using forEach() run the sumcheck() on all strings in the array
clean.forEach(sumCheck);
function sumCheck(string){
if((Number(string.charAt(0)) + Number(string.charAt(string.length - 1))) == 10){
result = true;
}else{
result = false;
}
}
return result;
}
QuestionsMarks("acc?7??sss?3rr1??????5");
The problem seems to come from Coderbyte that isn't able to parse correctly escaped characters in regex patterns (literals or with the RegExp constructor). So the simplest solution is to replace escaped sequences: \d => [0-9], and \? => [?] (as suggested by #Saud in comments).
About your approach:
... check if there are exactly 3 question marks between every pair of two numbers that add up to 10 ...
What does your corrected pattern /[0-9][?]{3}[0-9]/g?It looks for digits separated by three question marks (and then you check if the sum of two digits is 10). Even if this pattern would be able to find all pair of digits separated by three question marks in the string (that isn't the case(*)), It doesn't check if there are digits that add up to 10 and that aren't separated by exactly 3 question marks!
So, the goal is to find if the string contains a pair of digits that add up to 10 without the 3 question marks. If this pair exists the function returns false.
(*): Why /[0-9][?]{3}[0-9]/g isn't able to find all pair of digits separated by 3 question marks?
Example with: 1???2???3???4
Because you can't match the same character twice. The pattern will find: 1???2 and 3???4 but not 2???3 since the 2 is already consumed by the first match.
A possible way to do it:
function QuestionsMarks(str) {
var state = { d1: 0, d2: 0, marks: 0,
init: function() { this.d1 = this.d2; this.marks = 0; },
check: function() { return this.d1 + this.d2 > 9 && this.marks != 3; }
};
var re = /[0-9?]/g;
var m;
while ( (m = re.exec(str)) !== null ) {
if ( m[0] == '?' ) {
state.marks++;
} else {
state.d2 = parseInt(m[0]);
if ( state.check() ) return false;
state.init();
}
}
return true;
}
This question already has answers here:
How to get the last character of a string?
(15 answers)
Closed 8 years ago.
How can check the entered input is a valid question format using jquery ?
for eg: i have a string "How are you ?" . and i need to identify whether it is a
question or not .Do that all i need is to check whether the string ends with '?' ?. Thanks .
This will do the trick...
if (value.substr(-1) === "?") {
// do what you need here
}
string.substr(x) will start at the character with index x and go to the end of the string. This is normally a positive number so "abcdef".substr(2) returns "cdef". If you use a negative number then it counts from the end of the string backwards. "abcdef".substr(-2) returns "ef".
string.substr(-1) just returns the last character of the string.
If you want a cute endsWith function:
String.prototype.endsWith = function(pattern) {
var d = this.length - pattern.length;
return d >= 0 && this.lastIndexOf(pattern) === d;
};
console.log('Is this a question ?'.endsWith('?')); // true
Took the answer here.
You can use \?$ regex to find strings ending with ? mark.
var str = "what is your name?";
var patt = new RegExp("\? $");
if (patt.test(str))
{
// do your stuff
}
This question already has answers here:
Create RegExps on the fly using string variables
(6 answers)
Closed 8 years ago.
I have an array of alphabets in the form of letter strings
alpha = ['a','b', etc..];
I'm counting up numbers of each letter in a word like so
for (j=0;j<alpha.length;j++){
num = word.match(/alpha[j]/g).length;}
Problem is that, for example, alpha[0] is 'a', not a and match regex only recognizes a .
How can I convert from 'a' to a so that match recognizes it?
To clarify
"ara".match(/a/g) returns ["a","a"] while "ara".match(/'a'/g) returns null.
You can construct a RegExp from a string with the RegExp constructor as described here.
for (j=0;j<alpha.length;j++){
var matches = word.match(new RegExp(alpha[j], "g"));
if (matches) {
num = matches.length;
// other code here to process the match
}
}
This assumes that none of the characters in the alpha array will be special characters in a regular expression because if they are, you will have to escape them so they are treated as normal characters.
As jfriend00 suggests, you can use the RegExp constructor like:
var re, num, matches;
for (j=0; j<alpha.length; j++){
re = new RegExp(alpha[j],'g');
matches = word.match(re);
num = matches? matches.length : 0;
}
Note that another way (shorter, faster, simpler) is:
var num = word.split('a').length - 1; // 'ara' -> 2