Loop Statement-how to alternate on both sides - javascript

I'm trying to figure out how to alternate the "*" symbol on both sides of the string "a" within my do..while loop. I've changed a few things around, but ultimately no dice- I'm stumped on how to get the desired result. Does anyone have any suggestions on what I can do? This is the code I came up with:
function padIt(str,n){
var str="a", n= "*"
do{
str+=n;
n++;
} while(n<=5)
return str;
}

function padIt(str = "a", n = 0){
var pad = "*";
do {
if (n%2 === 0) str+=pad;
else str = pad + str;
n++;
} while(n<=5)
return str;
}
Padding alternation starts at the end when n is odd. You can swap the operations on the if and else statement if you want it to behave the other way.
padIt() // Output: '***a***'
padIt('TESTING',1) // Output: '***TESTING**'
padIt('TESTING',2) // Output: '**TESTING**'
padIt('TESTING',3) // Output: '**TESTING*'
padIt('TESTING',4) // Output: '*TESTING*'
padIt('TESTING',5) // Output: '*TESTING'
padIt('TESTING',6) // Output: 'TESTING*'
padIt('TESTING',7) // Output: '*TESTING'
// ...

Related

Can someone explain like I'm five how this counts how many letters are in a string without repeating?

I know what the code does, but I still don't understand it so I can repeat it myself. If anyone can help, that would be great!
function strLetterCount(string) {
const characters = {};
let str = "";
for (let character of string) {
characters[character] = characters[character] + 1 || 1;
}
for (let key in characters) {
str += `${key}${characters[key]}`
}
console.log(str);
return str;
}
strLetterCount("taco"); // "t1a1c1o1"
strLetterCount("coconut"); // "c2o2n1u1t1"
So if you follow the console.log in the below snippet, you'll be able to understand the working of the code. What it does is this:
There is an empty object characters={} which holds each character of the string as its key by iterating the string. At each iteration, if the key is not there, the object is assigned the key (which is character of string) and value is assigned as 1. If this key is already there, its value is simply increased. Finally all the key-value pair from this object is joined together and returned.
function strLetterCount(string) {
const characters = {};
let str = "";
for (let character of string) {
console.log(character)
characters[character] = characters[character] + 1 || 1;
console.log(characters)
}
for (let key in characters) {
str += `${key}${characters[key]}`
}
console.log(str);
return str;
}
strLetterCount("taco"); // "t1a1c1o1"
strLetterCount("coconut"); // "c2o2n1u1t1"
It creates an object ‘characters’ to keep a count of occurrences per character; then loops through the input string character by character, incrementing the corresponding counter in the ‘characters’ object each time.
The ‘characters’ object looks like this:
characters = {
“a”: 11,
“b”: 4,
“d”: 2,
...
}
Finally it goes through this object key by key and adds up the counts.
Let's imagine that you're 15 - then this should be enough :)
// you pass your string here
function strLetterCount(string) {
// this is object that will store letters and counts, like this:
// { "a": 1, "b": 3, "c": 2, ... }
const characters = {};
// this will be resulting string, like "a1b3c2"
let str = "";
// for each letter of `string`, put it in variable `character`
for (let character of string) {
// if `characters` object already has current letter - increase count by one
// otherwise - initialize it with 1
characters[character] = characters[character] + 1 || 1;
}
// for each letter in `characters` object
for (let key in characters) {
// add to resulting `str` letter followed by the number of occurrences
str += `${key}${characters[key]}`
}
// output result in console
console.log(str);
// return result
return str;
}
strLetterCount("taco"); // "t1a1c1o1"
strLetterCount("coconut"); // "c2o2n1u1t1"
Q : "Can someone explain like I'm five how this counts how many letters are in a string without repeating?"
Sure, with pleasure - let's run it step by step in an interactive IDE
The trick with a hidden surprise is in the first for(){...}-block :
function strLetterCount( string ) { // PARAMETER <string> (IN)
const characters = {}; // INITIALISED <characters>
let str = "CONTAINS: "; // INITIALISED <str>
//----------------------------------------------------------------------------------------------
for (let character of string) { // <iterate> over each <string>'s <character>
characters[character] = characters[character] + 1 || 1;
} // IF <character> already found in <characters> +1-it, IF NOT, store 1 "there"
//----------------------------------------------------------------------------------------------
for (let key in characters) { // <iterator> over each <key> in <characters>
str += `${key}:${characters[key]} ` // append <key>: and an integer count stored during <string> scanning above in <characters[key]>
}
//----------------------------------------------------------------------------------------------
console.log(str); // show the assembled <str> on console
return str; // return <str>
}
//----------------------------------------------------------------------------------------------
strLetterCount("taco"); // "CONTAINS: t:1 a:1 c:1 o:1 "
strLetterCount("coconut"); // "CONTAINS: c:2 o:2 n:1 u:1 t:1 "
strLetterCount("Can someone explain like I'm five how this counts how many letters are in a string without repeating?");
// // "CONTAINS: C:1 a:6 n:8 :17 s:5 o:6 m:3 e:10 x:1 p:2 l:3 i:8 k:1 I:1 ':1 f:1 v:1 h:4 w:3 t:8 c:1 u:2 y:1 r:4 g:2 ?:1 "

Is the input word in alphabetical order?

I'm writing a function that will return true or false in regards to whether or not the input string is in alphabetical order. I'm getting undefined and not sure what I'm missing
function is_alphabetic(str) {
let result = true;
for (let count = 1, other_count = 2; count >= str.length - 1, other_count >= str.length; count++,
other_count++) {
if (str.at[count] > str.at[other_count]) {
let result = false
}
return result
}
}
console.log(is_alphabetic('abc'));
you have put return statement inside the for loop, it should be outside the loop body.
Your code is also not correct. count should start from 0, other_count should start from 1.
count >= str.length - 1 should be count < str.length - 1 (this condition is completely unnecessary in your code because other_count < str.length should be the terminating condition in the loop)
and
other_count >= str.length should be other_count < str.length
Here's your corrected code
function is_alphabetic(str) {
let result = true;
for (let count = 0, other_count = 1; other_count < str.length; count++, other_count++) {
if (str[count] > str[other_count]) {
result = false
}
}
return result;
}
console.log(is_alphabetic('abc'));
Here's an alternative approach
function is_alphabetic(str){
return str.split('')
.every((c, idx) => str[idx + 1] ? c < str[idx + 1] : true);
}
console.log(is_alphabetic('abc'));
Keep in mind that if you want the comparisons between the characters to be case-insensitive, then convert the string in to lowercase before comparing the characters.
I think is easier if you compare the string using this function:
var sortAlphabets = function(text) {
return text.split('').sort().join('');
};
This produces results like:
sortAlphabets("abghi")
output: "abghi"
Or:
sortAlphabets("ibvjpqjk")
output: "bijjkpqv"
if you want to know if your string is alphabetically sorted, you might use:
var myString = "abcezxy"
sortAlphabets(myString) == myString
output: false
Or in case, you want to create an specific function:
function isSorted(myString) {
return sortAlphabets(myString) == myString
}
And for that case, you can use:
isSorted("abc")
var sortAlphabets = function(text) {
return text.split('').sort().join('');
};
function isSorted(myString) {
return sortAlphabets(myString) == myString
}
alert("is abc sorted: " + isSorted("abc"));
alert("is axb sorted: " + isSorted("axb"));
This should do it. I used .localeCompare() as this will ignore small/capital differences and will also deal reasonably with language specific characters, like German Umlauts.
function is_alphabetic(str){
return !str.split('').some((v,i,a)=>i&&v.localeCompare(a[i-1])<0)
}
['abcdefg','aacccRt','ashhe','xyz','aüv'].forEach(s=> console.log(s,is_alphabetic(s)) );
There are two issues in your code:
Your return statement is in your for-loop. To avoid such mistakes you can get a code-formatter like prettier;
Your for-loop condition is invalid. Keep in mind that the second part of the for-loop statement is supposed to be true to do an iteration and false to stop doing iterations. In this case, your condition count >= str.length-1, other_count >= str.length will first evaluate count >= str.length-1, discard the result because of the comma operator, evaluate other_count >= str.length which immediately resolves to false.
These two things together make it so your function never returns, which the javascript runtime interprets as undefined.
Hope this helps you understand what went wrong. But like many other pointed out, there are better ways to tackle the problem you're trying to solve.
You just have to compare the string with its corresponding 'sorted' one
let string = 'abc'.split('').join('');
let sortedString = 'abc'.split('').sort().join('');
console.log(sortedString === sortedString)
let string2 = 'dbc'.split('').join('');
let sortedString2 = 'dbc'.split('').sort().join('');
console.log(string2 === sortedString2)

Alphabet from numbers without delimiters

If we had our input as "1125" and the maximum value as 26 for example, then our output would be:
[ [1,1,2,5] , [11,2,5] , [1,12,5] , [1,1,25] , [11,25] ]
that's an array that consists of every possible way to separate the characters to be less than the value 26.
We can use this to decrypt messages that have been converted letters into alphabetical numbers but without delimiters.
Here's my current code that's my first try to solve this:
Array.prototype.indexOfArray=function(array){
for(var i=0;i<this.length;i++){
if(this[i].length==array.length){
var same=true;
for(var j=0;j<this[i].length;j++){
if(this[i][j]!=array[j]){
same=false;
break;
}
}
if(same){
return i;
}
}
}
return-1;
};
function possibilities(string,max){ //The function I'm talking about.
var output=[];
(function collector(array,held,start){
for(var i=start;i<string.length;i++){
var char=string[i];
if(Number(held+char)>max){
array.push(held);
held=char;
}else{
held+=char;
if(i!=string.length-1){
collector(array.slice().concat(held),"",i+1);
}
}
}
if(held.length>0){
array.push(held);
}
if(output.indexOfArray(array)==-1){
output.push(array);
}
})([],"",0);
return output;
}
var message="302213"; //"dawn" is "3 0 22 13" with delimiters
var alphabet="abcdefghijklmnopqrstuvwxyz";
var solutions=possibilities(message,alphabet.length);
for(var i=0;i<solutions.length;i++){
console.log(solutions[i].join(",")+" : "+solutions[i].map(x=>alphabet[Number(x)]).join(""));
}
And prints out:
3,0,2,2,1,3 : daccbd
3,0,2,2,13 : daccn
3,0,2,21,3 : dacvd
3,0,22,1,3 : dawbd
3,0,22,13 : dawn
3,02,2,1,3 : dccbd
3,02,2,13 : dccn
3,02,21,3 : dcvd
3,022,1,3 : dwbd
3,022,13 : dwn
How could I improve this? What's the name of this algorithm?
You could use a different approch for glueing parts together, with 2array.length - 1 as formular for different chunked parts. Then filter the ones out, which have a value greater than 25.
function split(string) {
var array = string.split(''),
result = [],
i, l = 1 << (array.length - 1),
v, j,
temp;
for (i = 0; i < l; i++) {
v = i;
temp = [array[0]];
for (j = 1; j < array.length; j++) {
if (v & 1) {
temp[temp.length - 1] += array[j];
} else {
temp.push(array[j]);
}
v = v >> 1;
}
result.push(temp);
}
return result.filter(function (a) {
return a.every(function (b) {
return b < 26;
});
});
}
function output(array) {
array.forEach(function (a) {
console.log(a.join(), a.map(function (b) { return (+b + 10).toString(36); }).join(''));
});
}
output(split('302213'));
output(split('1125'));
.as-console-wrapper { max-height: 100% !important; top: 0; }
this is nice example for recursive approach. Let us do some definitions first
Input
Input lowercase string <'a','z'> is encoded to <1,26> without delimiters.
output
we want to obtain all decoding of string combinations for each valid decoding 1 vs. 2 digit codes.
Heuristics
so 2 digit codes can start with { 1,2 } and { 0 } means that we are handlin 2 digit code { 10,20 } or { 0 } for <0,25> this can be used to lower the combinations number.
Recursive algorithm
if we have some function like decode(in); then we can recursively do this in simple manner like this:
decode (string in)
{
l=in.Length();
add_combination(tochar(in[1]) + in.substring(2,l-1));
add_combination(tochar(10*in[1]+in[2]) + in.substring(3,l-2));
}
In plain words take first 1 or 2 digit character and decode the rest of the string. Let assume your example 1125 the recursions will be as this:
||decode(1125)|
|1|decode(125)|
|1,1|decode(25)|
|1,1,2|decode(5)|
|1,1,2,5|decode()| - combination
|1,1,25|decode()| - combination
|1,12|decode(5)|
|1,12,5|decode()| - combination
|11|decode(25)|
|11,2|decode(5)|
|11,2,5|decode()| - combination
|11,25|decode()| - combination
The intendation represent recursion layer, the first part is current combination prefix (in0) and right part is the rest of string to decode (in1+i).
This sounds easy but to code this kind of feedback is bit more complicated. That is because wee need to remember a list of solutions instead of one. I decided to store all results in single string separated by \r\l end of lines. Here working VCL/C++ example:
//---------------------------------------------------------------------------
AnsiString txt_encode0(const AnsiString &in) // <'a','z'> -> <0,25>
{
int i,l=in.Length();
AnsiString txt="";
for (i=1;i<=l;i++) txt+=int(in[i]-'a');
return txt;
}
//---------------------------------------------------------------------------
AnsiString txt_encode1(const AnsiString &in) // <'a','z'> -> <1,26>
{
int i,l=in.Length();
AnsiString txt="";
for (i=1;i<=l;i++) txt+=int(in[i]-'a'+1);
return txt;
}
//---------------------------------------------------------------------------
void txt_decode0(AnsiString &out,AnsiString in0,const AnsiString &in1,int i,int &l) // recursion <0,25> -> <'a','z'>
{
// stop recursion if whole string processed
if (i>l) { out+=in0+"\r\n"; return; }
int a0,a1;
// load first 2 digits from i if second digit is not applicable set is as -1
a0=in1[i]-'0'; i++;
if (i<= l) a1=in1[i]-'0'; else a1=-1;
if (a0> 2) a1=-1; // >2 means always 1 digit code
if (a0==0) a1=-1; // =0 means always 1 digit code
// one digit combination
in0+=char(a0+'a');
txt_decode0(out,in0,in1,i,l);
in0.SetLength(in0.Length()-1);
// 2 digit combination
if (a1>=0)
{
a0*=10;
a0+=a1; i++;
if (a0<=26)
{
in0+=char(a0+'a');
txt_decode0(out,in0,in1,i,l);
}
}
}
AnsiString txt_decode0(const AnsiString &in) // <0,25> -> <'a','z'>
{
int l=in.Length();
AnsiString in0="",out="";
txt_decode0(out,in0,in,1,l);
return out;
}
//---------------------------------------------------------------------------
void txt_decode1(AnsiString &out,AnsiString in0,const AnsiString &in1,int i,int &l) // recursion <1,26> -> <'a','z'>
{
// stop recursion if whole string processed
if (i>l) { out+=in0+"\r\n"; return; }
int a0,a1;
// load first 2 digits from i if second digit is not applicable set is as -1
a0=in1[i]-'0'; i++;
if (i<=l) a1=in1[i]-'0'; else a1=-1;
if (a0> 2) a1=-1; // >2 means always 1 digit code
// one digit combination
if (a1!=0) // =0 means always 2 digit code
{
in0+=char(a0+'a'-1);
txt_decode1(out,in0,in1,i,l);
in0.SetLength(in0.Length()-1);
}
// 2 digit combination
if (a1>=0)
{
a0*=10;
a0+=a1; i++;
if (a0<=26)
{
in0+=char(a0+'a'-1);
txt_decode1(out,in0,in1,i,l);
}
}
}
AnsiString txt_decode1(const AnsiString &in) // <1,26> -> <'a','z'>
{
int l=in.Length();
AnsiString in0="",out="";
txt_decode1(out,in0,in,1,l);
return out;
}
//---------------------------------------------------------------------------
void main()
{
AnsiString enc,dec,txt;
txt="decoding";
enc=txt_encode0(txt);
// enc="302213";
dec=txt_decode0(enc);
}
//---------------------------------------------------------------------------
The txt_encode0,txt_decode0 operates on <0,25> and txt_encode1,txt_decode1 operates on <1,26> range.
The out is holding list of valid combinations. in0 holds actual prefix of combination in1 hold the input string. i is start index for actual combination in in1 and l is length of in1. Here the output for <0,25>:
message:decoding
encoded:3421438136
decoded in [ 0.013 ms]
decbedibdg
decbeding
decodibdg
decoding
devedibdg
deveding
and your sample:
encoded:302213
decoded in [ 0.007 ms]
daccbd
daccn
dacvd
dawbd
dawn
I am using AnsiString from VCL they are self allocating dynamic strings with indexing from 1. For example AnsiString s="abc"; s[1]=='a' The size of it is s.Length() so s[s.Length()]=='c'.
Here's a recursive approach in JavaScript. The idea is if the next two characters in the string can be interpreted in two ways, add each of the two ways to each result in splitting the next part of the string. Otherwise, add just the first character to each result in splitting the next part of the string.
function possibilities(str){
if (str.length === 0) return [[]];
var result = [], next = possibilities(str.substr(1));
for (var i=0; i<next.length; i++)
result.push([str[0]].concat(next[i]));
if (str.length > 1 && str[0] !== '0' && str.substr(0,2) < 27){
next = possibilities(str.substr(2));
for (var i=0; i<next.length; i++)
result.push([str.substr(0,2)].concat(next[i]));
}
return result;
}
console.log(possibilities('1125'));
console.log(possibilities('302213'));

How to write palindrome in JavaScript

I wonder how to write palindrome in javascript, where I input different words and program shows if word is palindrome or not. For example word noon is palindrome, while bad is not.
Thank you in advance.
function palindrome(str) {
var len = str.length;
var mid = Math.floor(len/2);
for ( var i = 0; i < mid; i++ ) {
if (str[i] !== str[len - 1 - i]) {
return false;
}
}
return true;
}
palindrome will return if specified word is palindrome, based on boolean value (true/false)
UPDATE:
I opened bounty on this question due to performance and I've done research and here are the results:
If we are dealing with very large amount of data like
var abc = "asdhfkahkjdfhkaksjdfhaksdfjhakjddfhkjahksdhfaiuyqewiuryiquweyriyqiuweyriuqiuweryiquweyriuqyweirukajsdhfkahdfjkhakjsdhfkahksdhfakhdjkfqwiueryqiueyriuasdkfjhakjhdfkjashfkajhsdfkjahsdkalsdjflkasjdfljqoiweurasldjflasfdasdhfkahkjdfhkaksjdfhaksdfjhakjddfhkjahksdhfaiuyqewiuryiquweyriyqiuweyriuqiuweryiquweyriuqyweirukajsdhfkahdfjkhakjsdhfkahksdhfakhdjkfqwiueryqiueyriuasdkfjhakjhdfkjashfkajhsdfkjahsdkalsdjflkasjdfljqoiweurasldjflasfdasdhfkahkjdfhkaksjdfhaksdfjhakjddfhkjahksdhfaiuyqewiuryiquweyriyqiuweyriuqiuweryiquweyriuqyweirukajsdhfkahdfjkhakjsdhfkahksdhfakhdjkfqwiueryqiueyriuasdkfjhakjhdfkjashfkajhsdfkjahsdkalsdjflkasjdfljqoiweurasldjflasfdasdhfkahkjdfhkaksjdfhaksdfjhakjddfhkjahksdhfaiuyqewiuryiquweyriyqiuweyriuqiuweryiquweyriuqyweirukajsdhfkahdfjkhakjsdhfkahksdhfakhdjkfqwiueryqiueyriuasdkfjhakjhdfkjashfkajhsdfkjahsdkalsdjflkasjdfljqoiweurasldjflasfdasdhfkahkjdfhkaksjdfhaksdfjhakjddfhkjahksdhfaiuyqewiuryiquweyriyqiuweyriuqiuweryiquweyriuqyweirukajsdhfkahdfjkhakjsdhfkahksdhfakhdjkfqwiueryqiueyriuasdkfjhakjhdfkjashfkajhsdfkjahsdkalsdjflkasjdfljqoiweurasldjflasfdasdhfkahkjdfhkaksjdfhaksdfjhakjddfhkjahksdhfaiuyqewiuryiquweyriyqiuweyriuqiuweryiquweyriuqyweirukajsdhfkahdfjkhakjsdhfkahksdhfakhdjkfqwiueryqiueyriuasdkfjhakjhdfkjashfkajhsdfkjahsdkalsdjflkasjdfljqoiweurasldjflasfdasdhfkahkjdfhkaksjdfhaksdfjhakjddfhkjahksdhfaiuyqewiuryiquweyriyqiuweyriuqiuweryiquweyriuqyweirukajsdhfkahdfjkhakjsdhfkahksdhfakhdjkfqwiueryqiueyriuasdkfjhakjhdfkjashfkajhsdfkjahsdkalsdjflkasjdfljqoiweurasldjflasfdasdhfkahkjdfhkaksjdfhaksdfjhakjddfhkjahksdhfaiuyqewiuryiquweyriyqiuweyriuqiuweryiquweyriuqyweirukajsdhfkahdfjkhakjsdhfkahksdhfakhdjkfqwiueryqiueyriuasdkfjhakjhdfkjashfkajhsdfkjahsdkalsdjflkasjdfljqoiweurasldjflasfdasdhfkahkjdfhkaksjdfhaksdfjhakjddfhkjahksdhfaiuyqewiuryiquweyriyqiuweyriuqiuweryiquweyriuqyweirukajsdhfkahdfjkhakjsdhfkahksdhfakhdjkfqwiueryqiueyriuasdkfjhakjhdfkjashfkajhsdfkjahsdkalsdjflkasjdfljqoiweurasldjflasfdasdhfkahkjdfhkaksjdfhaksdfjhakjddfhkjahksdhfaiuyqewiuryiquweyriyqiuweyriuqiuweryiquweyriuqyweirukajsdhfkahdfjkhakjsdhfkahksdhfakhdjkfqwiueryqiueyriuasdkfjhakjhdfkjashfkajhsdfkjahsdkalsdjflkasjdfljqoiweurasldjflasfdasdhfkahkjdfhkaksjdfhaksdfjhakjddfhkjahksdhfaiuyqewiuryiquweyriyqiuweyriuqiuweryiquweyriuqyweirukajsdhfkahdfjkhakjsdhfkahksdhfakhdjkfqwiueryqiueyriuasdkfjhakjhdfkjashfkajhsdfkjahsdkalsdjflkasjdfljqoiweurasldjflasfdasdhfkahkjdfhkaksjdfhaksdfjhakjddfhkjahksdhfaiuyqewiuryiquweyriyqiuweyriuqiuweryiquweyriuqyweirukajsdhfkahdfjkhakjsdhfkahksdhfakhdjkfqwiueryqiueyriuasdkfjhakjhdfkjashfkajhsdfkjahsdkalsdjflkasjdfljqoiweurasldjflasfdasdhfkahkjdfhkaksjdfhaksdfjhakjddfhkjahksdhfaiuyqewiuryiquweyriyqiuweyriuqiuweryiquweyriuqyweirukajsdhfkahdfjkhakjsdhfkahksdhfakhdjkfqwiueryqiueyriuasdkfjhakjhdfkjashfkajhsdfkjahsdkalsdjflkasjdfljqoiweurasldjflasfdasdhfkahkjdfhkaksjdfhaksdfjhakjddfhkjahksdhfaiuyqewiuryiquweyriyqiuweyriuqiuweryiquweyriuqyweirukajsdhfkahdfjkhakjsdhfkahksdhfakhdjkfqwiueryqiueyriuasdkfjhakjhdfkjashfkajhsdfkjahsdkalsdjflkasjdfljqoiweurasldjflasfdasdhfkahkjdfhkaksjdfhaksdfjhakjddfhkjahksdhfaiuyqewiuryiquweyriyqiuweyriuqiuweryiquweyriuqyweirukajsdhfkahdfjkhakjsdhfkahksdhfakhdjkfqwiueryqiueyriuasdkfjhakjhdfkjashfkajhsdfkjahsdkalsdjflkasjdfljqoiweurasldjflasfdasdhfkahkjdfhkaksjdfhaksdfjhakjddfhkjahksdhfaiuyqewiuryiquweyriyqiuweyriuqiuweryiquweyriuqyweirukajsdhfkahdfjkhakjsdhfkahksdhfakhdjkfqwiueryqiueyriuasdkfjhakjhdfkjashfkajhsdfkjahsdkalsdjflkasjdfljqoiweurasldjflasfdasdhfkahkjdfhkaksjdfhaksdfjhakjddfhkjahksdhfaiuyqewiuryiquweyriyqiuweyriuqiuweryiquweyriuqyweirukajsdhfkahdfjkhakjsdhfkahksdhfakhdjkfqwiueryqiueyriuasdkfjhakjhdfkjashfkajhsdfkjahsdkalsdjflkasjdfljqoiweurasldjflasfdasdhfkahkjdfhkaksjdfhaksdfjhakjddfhkjahksdhfaiuyqewiuryiquweyriyqiuweyriuqiuweryiquweyriuqyweirukajsdhfkahdfjkhakjsdhfkahksdhfakhdjkfqwiueryqiueyriuasdkfjhakjhdfkjashfkajhsdfkjahsdkalsdjflkasjdfljqoiweurasldjflasfdasdhfkahkjdfhkaksjdfhaksdfjhakjddfhkjahksdhfaiuyqewiuryiquweyriyqiuweyriuqiuweryiquweyriuqyweirukajsdhfkahdfjkhakjsdhfkahksdhfakhdjkfqwiueryqiueyriuasdkfjhakjhdfkjashfkajhsdfkjahsdkalsdjflkasjdfljqoiweurasldjflasfdasdhfkahkjdfhkaksjdfhaksdfjhakjddfhkjahksdhfaiuyqewiuryiquweyriyqiuweyriuqiuweryiquweyriuqyweirukajsdhfkahdfjkhakjsdhfkahksdhfakhdjkfqwiueryqiueyriuasdkfjhakjhdfkjashfkajhsdfkjahsdkalsdjflkasjdfljqoiweurasldjflasfdasdhfkahkjdfhkaksjdfhaksdfjhakjddfhkjahksdhfaiuyqewiuryiquweyriyqiuweyriuqiuweryiquweyriuqyweirukajsdhfkahdfjkhakjsdhfkahksdhfakhdjkfqwiueryqiueyriuasdkfjhakjhdfkjashfkajhsdfkjahsdkalsdjflkasjdfljqoiweurasldjflasfd";
for ( var i = 0; i < 10; i++ ) {
abc += abc; // making string even more larger
}
function reverse(s) { // using this method for second half of string to be embedded
return s.split("").reverse().join("");
}
abc += reverse(abc); // adding second half string to make string true palindrome
In this example palindrome is True, just to note
Posted palindrome function gives us time from 180 to 210 Milliseconds (in current example), and the function posted below
with string == string.split('').reverse().join('') method gives us 980 to 1010 Milliseconds.
Machine Details:
System: Ubuntu 13.10
OS Type: 32 Bit
RAM: 2 Gb
CPU: 3.4 Ghz*2
Browser: Firefox 27.0.1
Try this:
var isPalindrome = function (string) {
if (string == string.split('').reverse().join('')) {
alert(string + ' is palindrome.');
}
else {
alert(string + ' is not palindrome.');
}
}
document.getElementById('form_id').onsubmit = function() {
isPalindrome(document.getElementById('your_input').value);
}
So this script alerts the result, is it palindrome or not. You need to change the your_id with your input id and form_id with your form id to get this work.
Demo!
Use something like this
function isPalindrome(s) {
return s === s.split("").reverse().join("") ? true : false;
}
alert(isPalindrome("noon"));
alternatively the above code can be optimized as [updated after rightfold's comment]
function isPalindrome(s) {
return s === s.split("").reverse().join("");
}
alert(isPalindrome("malayalam"));
alert(isPalindrome("english"));
Faster Way:
-Compute half the way in loop.
-Store length of the word in a variable instead of calculating every time.
EDIT:
Store word length/2 in a temporary variable as not to calculate every time in the loop as pointed out by (mvw) .
function isPalindrome(word){
var i,wLength = word.length-1,wLengthToCompare = wLength/2;
for (i = 0; i <= wLengthToCompare ; i++) {
if (word.charAt(i) != word.charAt(wLength-i)) {
return false;
}
}
return true;
}
Let us start from the recursive definition of a palindrome:
The empty string '' is a palindrome
The string consisting of the character c, thus 'c', is a palindrome
If the string s is a palindrome, then the string 'c' + s + 'c' for some character c is a palindrome
This definition can be coded straight into JavaScript:
function isPalindrome(s) {
var len = s.length;
// definition clauses 1. and 2.
if (len < 2) {
return true;
}
// note: len >= 2
// definition clause 3.
if (s[0] != s[len - 1]) {
return false;
}
// note: string is of form s = 'a' + t + 'a'
// note: s.length >= 2 implies t.length >= 0
var t = s.substr(1, len - 2);
return isPalindrome(t);
}
Here is some additional test code for MongoDB's mongo JavaScript shell, in a web browser with debugger replace print() with console.log()
function test(s) {
print('isPalindrome(' + s + '): ' + isPalindrome(s));
}
test('');
test('a');
test('ab');
test('aa');
test('aab');
test('aba');
test('aaa');
test('abaa');
test('neilarmstronggnortsmralien');
test('neilarmstrongxgnortsmralien');
test('neilarmstrongxsortsmralien');
I got this output:
$ mongo palindrome.js
MongoDB shell version: 2.4.8
connecting to: test
isPalindrome(): true
isPalindrome(a): true
isPalindrome(ab): false
isPalindrome(aa): true
isPalindrome(aab): false
isPalindrome(aba): true
isPalindrome(aaa): true
isPalindrome(abaa): false
isPalindrome(neilarmstronggnortsmralien): true
isPalindrome(neilarmstrongxgnortsmralien): true
isPalindrome(neilarmstrongxsortsmralien): false
An iterative solution is:
function isPalindrome(s) {
var len = s.length;
if (len < 2) {
return true;
}
var i = 0;
var j = len - 1;
while (i < j) {
if (s[i] != s[j]) {
return false;
}
i += 1;
j -= 1;
}
return true;
}
Look at this:
function isPalindrome(word){
if(word==null || word.length==0){
// up to you if you want true or false here, don't comment saying you
// would put true, I put this check here because of
// the following i < Math.ceil(word.length/2) && i< word.length
return false;
}
var lastIndex=Math.ceil(word.length/2);
for (var i = 0; i < lastIndex && i< word.length; i++) {
if (word[i] != word[word.length-1-i]) {
return false;
}
}
return true;
}
Edit: now half operation of comparison are performed since I iterate only up to half word to compare it with the last part of the word. Faster for large data!!!
Since the string is an array of char no need to use charAt functions!!!
Reference: http://wiki.answers.com/Q/Javascript_code_for_palindrome
Taking a stab at this. Kind of hard to measure performance, though.
function palin(word) {
var i = 0,
len = word.length - 1,
max = word.length / 2 | 0;
while (i < max) {
if (word.charCodeAt(i) !== word.charCodeAt(len - i)) {
return false;
}
i += 1;
}
return true;
}
My thinking is to use charCodeAt() instead charAt() with the hope that allocating a Number instead of a String will have better perf because Strings are variable length and might be more complex to allocate. Also, only iterating halfway through (as noted by sai) because that's all that's required. Also, if the length is odd (ex: 'aba'), the middle character is always ok.
Best Way to check string is palindrome with more criteria like case and special characters...
function checkPalindrom(str) {
var str = str.replace(/[^a-zA-Z0-9]+/gi, '').toLowerCase();
return str == str.split('').reverse().join('');
}
You can test it with following words and strings and gives you more specific result.
1. bob
2. Doc, note, I dissent. A fast never prevents a fatness. I diet on cod
For strings it ignores special characters and convert string to lower case.
String.prototype.isPalindrome = function isPalindrome() {
const cleanString = this.toLowerCase().replace(/\s+/g, '');
const cleanStringRevers = cleanString.split("").reverse().join("");
return cleanString === cleanStringRevers;
}
let nonPalindrome = 'not a palindrome';
let palindrome = 'sugus';
console.log(nonPalindrome.isPalindrome())
console.log(palindrome.isPalindrome())
The most important thing to do when solving a Technical Test is Don't use shortcut methods -- they want to see how you think algorithmically! Not your use of methods.
Here is one that I came up with (45 minutes after I blew the test). There are a couple optimizations to make though. When writing any algorithm, its best to assume false and alter the logic if its looking to be true.
isPalindrome():
Basically, to make this run in O(N) (linear) complexity you want to have 2 iterators whose vectors point towards each other. Meaning, one iterator that starts at the beginning and one that starts at the end, each traveling inward. You could have the iterators traverse the whole array and use a condition to break/return once they meet in the middle, but it may save some work to only give each iterator a half-length by default.
for loops seem to force the use of more checks, so I used while loops - which I'm less comfortable with.
Here's the code:
/**
* TODO: If func counts out, let it return 0
* * Assume !isPalindrome (invert logic)
*/
function isPalindrome(S){
var s = S
, len = s.length
, mid = len/2;
, i = 0, j = len-1;
while(i<mid){
var l = s.charAt(i);
while(j>=mid){
var r = s.charAt(j);
if(l === r){
console.log('#while *', i, l, '...', j, r);
--j;
break;
}
console.log('#while !', i, l, '...', j, r);
return 0;
}
++i;
}
return 1;
}
var nooe = solution('neveroddoreven'); // even char length
var kayak = solution('kayak'); // odd char length
var kayaks = solution('kayaks');
console.log('#isPalindrome', nooe, kayak, kayaks);
Notice that if the loops count out, it returns true. All the logic should be inverted so that it by default returns false. I also used one short cut method String.prototype.charAt(n), but I felt OK with this as every language natively supports this method.
This function will remove all non-alphanumeric characters (punctuation, spaces, and symbols) and turn everything lower case in order to check for palindromes.
function palindrome(str){
var re = /[^A-Za-z0-9]/g;
str = str.toLowerCase().replace(re, '');
return str == str.split('').reverse().join('') ? true : false;
}
Here is an optimal and robust solution for checking string palindrome using ES6 features.
const str="madam"
var result=[...str].reduceRight((c,v)=>((c+v)))==str?"Palindrome":"Not Palindrome";
console.log(result);
Try this
isPalindrome = (string) => {
if (string === string.split('').reverse().join('')) {
console.log('is palindrome');
}
else {
console.log('is not palindrome');
}
}
isPalindrome(string)
Here's a one-liner without using String.reverse,
const isPal = str => [...new Array(strLen = str.length)]
.reduce((acc, s, i) => acc + str[strLen - (i + 1)], '') === str;
function palindrome(str) {
var lenMinusOne = str.length - 1;
var halfLen = Math.floor(str.length / 2);
for (var i = 0; i < halfLen; ++i) {
if (str[i] != str[lenMinusOne - i]) {
return false;
}
}
return true;
}
Optimized for half string parsing and for constant value variables.
I think following function with time complexity of o(log n) will be better.
function palindrom(s){
s = s.toString();
var f = true; l = s.length/2, len = s.length -1;
for(var i=0; i < l; i++){
if(s[i] != s[len - i]){
f = false;
break;
}
}
return f;
}
console.log(palindrom(12321));
Here's another way of doing it:
function isPalin(str) {
str = str.replace(/\W/g,'').toLowerCase();
return(str==str.split('').reverse().join(''));
}
Below code tells how to get a string from textBox and tell you whether it is a palindrome are not & displays your answer in another textbox
<html>
<head>
<meta charset="UTF-8"/>
<link rel="stylesheet" href=""/>
</head>
<body>
<h1>1234</h1>
<div id="demo">Example</div>
<a accessKey="x" href="http://www.google.com" id="com" >GooGle</a>
<h1 id="tar">"This is a Example Text..."</h1>
Number1 : <input type="text" name="txtname" id="numb"/>
Number2 : <input type="text" name="txtname2" id="numb2"/>
Number2 : <input type="text" name="txtname3" id="numb3" />
<button type="submit" id="sum" onclick="myfun()" >count</button>
<button type="button" id="so2" onclick="div()" >counnt</button><br/><br/>
<ol>
<li>water</li>
<li>Mazaa</li>
</ol><br/><br/>
<button onclick="myfun()">TryMe</button>
<script>
function myfun(){
var pass = document.getElementById("numb").value;
var rev = pass.split("").reverse().join("");
var text = document.getElementById("numb3");
text.value = rev;
if(pass === rev){
alert(pass + " is a Palindrome");
}else{
alert(pass + " is Not a Palindrome")
}
}
</script>
</body>
</html>
25x faster + recursive + non-branching + terse
function isPalindrome(s,i) {
return (i=i||0)<0||i>=s.length>>1||s[i]==s[s.length-1-i]&&isPalindrome(s,++i);
}
See my complete explanation here.
The code is concise quick fast and understandable.
TL;DR
Explanation :
Here isPalindrome function accepts a str parameter which is typeof string.
If the length of the str param is less than or equal to one it simply returns "false".
If the above case is false then it moves on to the second if statement and checks that if the character at 0 position of the string is same as character at the last place. It does an inequality test between the both.
str.charAt(0) // gives us the value of character in string at position 0
str.slice(-1) // gives us the value of last character in the string.
If the inequality result is true then it goes ahead and returns false.
If result from the previous statement is false then it recursively calls the isPalindrome(str) function over and over again until the final result.
function isPalindrome(str){
if (str.length <= 1) return true;
if (str.charAt(0) != str.slice(-1)) return false;
return isPalindrome(str.substring(1,str.length-1));
};
document.getElementById('submit').addEventListener('click',function(){
var str = prompt('whats the string?');
alert(isPalindrome(str))
});
document.getElementById('ispdrm').onsubmit = function(){alert(isPalindrome(document.getElementById('inputTxt').value));
}
<!DOCTYPE html>
<html>
<body>
<form id='ispdrm'><input type="text" id="inputTxt"></form>
<button id="submit">Click me</button>
</body>
</html>
function palindrome(str) {
var re = /[^A-Za-z0-9]/g;
str = str.toLowerCase().replace(re, '');
var len = str.length;
for (var i = 0; i < len/2; i++) {
if (str[i] !== str[len - 1 - i]) {
return false;
}
}
return true;
}
Or you could do it like this.
var palindrome = word => word == word.split('').reverse().join('')
How about this one?
function pall (word) {
var lowerCWord = word.toLowerCase();
var rev = lowerCWord.split('').reverse().join('');
return rev.startsWith(lowerCWord);
}
pall('Madam');
str1 is the original string with deleted non-alphanumeric characters and spaces and str2 is the original string reversed.
function palindrome(str) {
var str1 = str.toLowerCase().replace(/\s/g, '').replace(
/[^a-zA-Z 0-9]/gi, "");
var str2 = str.toLowerCase().replace(/\s/g, '').replace(
/[^a-zA-Z 0-9]/gi, "").split("").reverse().join("");
if (str1 === str2) {
return true;
}
return false;
}
palindrome("almostomla");
function isPalindrome(s) {
return s == reverseString(s);
}
console.log((isPalindrome("abcba")));
function reverseString(str){
let finalStr=""
for(let i=str.length-1;i>=0;i--){
finalStr += str[i]
}
return finalStr
}
Frist I valid this word with converting lowercase and removing whitespace and then compare with reverse word within parameter word.
function isPalindrome(input) {
const toValid = input.trim("").toLowerCase();
const reverseWord = toValid.split("").reverse().join("");
return reverseWord == input.toLowerCase().trim() ? true : false;
}
isPalindrome(" madam ");
//true
This answer is easy to read and I tried to explain by using comment. Check the code below for How to write Palindrome in JavaScript.
Step 1: Remove all non-alphanumeric characters (punctuation, spaces and symbols) from Argument string 'str' using replace() and then convert in to lowercase using toLowerCase().
Step 2: Now make string reverse. first split the string into the array using split() then reverse the array using reverse() then make the string by joining array elements using join() .
Step 3: Find the first character of nonAlphaNumeric string using charAt(0).
Step 4: Find the Last character of nonAlphaNumeric string using charAt(length of nonAlphaNumeric string - 1).
Step 5: Use If condition to chack nonAlphaNumeric string and reverse string is same or not.
Step 6: Use another If condition to chack first character of nonAlphaNumeric string is same to Last character of nonAlphaNumeric string.
function palindrome(str) {
var nonAlphaNumericStr = str.replace(/[^0-9A-Za-z]/g, "").toLowerCase(); // output - e1y1e
var reverseStr = nonAlphaNumericStr.split("").reverse().join(""); // output - e1y1e
var firstChar = nonAlphaNumericStr.charAt(0); // output - e
var lastChar = nonAlphaNumericStr.charAt(nonAlphaNumericStr.length - 1); // output - e
if(nonAlphaNumericStr === reverseStr) {
if(firstChar === lastChar) {
return `String is Palindrome`;
}
}
return `String is not Palindrome`;
}
console.log(palindrome("_eye"));
function check(txt)
{
for (var i = txt.length; i >= 0; i--)
if (txt[i] !== txt[txt.length - 1 - i])
return console.log('not palidrome');
return console.log(' palidrome');
}
check('madam');
Note: This is case sensitive
function palindrome(word)
{
for(var i=0;i<word.length/2;i++)
if(word.charAt(i)!=word.charAt(word.length-(i+1)))
return word+" is Not a Palindrome";
return word+" is Palindrome";
}
Here is the fiddle: http://jsfiddle.net/eJx4v/
I am not sure how this JSPerf check the code performance. I just tried to reverse the string & check the values. Please comment about the Pros & Cons of this method.
function palindrome(str) {
var re = str.split(''),
reArr = re.slice(0).reverse();
for (a = 0; a < re.length; a++) {
if (re[a] == reArr[a]) {
return false;
} else {
return true;
}
}
}
JS Perf test

How to count string occurrence in string?

How can I count the number of times a particular string occurs in another string. For example, this is what I am trying to do in Javascript:
var temp = "This is a string.";
alert(temp.count("is")); //should output '2'
The g in the regular expression (short for global) says to search the whole string rather than just find the first occurrence. This matches is twice:
var temp = "This is a string.";
var count = (temp.match(/is/g) || []).length;
console.log(count);
And, if there are no matches, it returns 0:
var temp = "Hello World!";
var count = (temp.match(/is/g) || []).length;
console.log(count);
/** Function that count occurrences of a substring in a string;
* #param {String} string The string
* #param {String} subString The sub string to search for
* #param {Boolean} [allowOverlapping] Optional. (Default:false)
*
* #author Vitim.us https://gist.github.com/victornpb/7736865
* #see Unit Test https://jsfiddle.net/Victornpb/5axuh96u/
* #see https://stackoverflow.com/a/7924240/938822
*/
function occurrences(string, subString, allowOverlapping) {
string += "";
subString += "";
if (subString.length <= 0) return (string.length + 1);
var n = 0,
pos = 0,
step = allowOverlapping ? 1 : subString.length;
while (true) {
pos = string.indexOf(subString, pos);
if (pos >= 0) {
++n;
pos += step;
} else break;
}
return n;
}
Usage
occurrences("foofoofoo", "bar"); //0
occurrences("foofoofoo", "foo"); //3
occurrences("foofoofoo", "foofoo"); //1
allowOverlapping
occurrences("foofoofoo", "foofoo", true); //2
Matches:
foofoofoo
1 `----´
2 `----´
Unit Test
https://jsfiddle.net/Victornpb/5axuh96u/
Benchmark
I've made a benchmark test and my function is more then 10 times
faster then the regexp match function posted by gumbo. In my test
string is 25 chars length. with 2 occurences of the character 'o'. I
executed 1 000 000 times in Safari.
Safari 5.1
Benchmark> Total time execution: 5617 ms (regexp)
Benchmark> Total time execution: 881 ms (my function 6.4x faster)
Firefox 4
Benchmark> Total time execution: 8547 ms (Rexexp)
Benchmark> Total time execution: 634 ms (my function 13.5x faster)
Edit: changes I've made
cached substring length
added type-casting to string.
added optional 'allowOverlapping' parameter
fixed correct output for "" empty substring case.
Gist
https://gist.github.com/victornpb/7736865
function countInstances(string, word) {
return string.split(word).length - 1;
}
console.log(countInstances("This is a string", "is"))
You can try this:
var theString = "This is a string.";
console.log(theString.split("is").length - 1);
My solution:
var temp = "This is a string.";
function countOccurrences(str, value) {
var regExp = new RegExp(value, "gi");
return (str.match(regExp) || []).length;
}
console.log(countOccurrences(temp, 'is'));
You can use match to define such function:
String.prototype.count = function(search) {
var m = this.match(new RegExp(search.toString().replace(/(?=[.\\+*?[^\]$(){}\|])/g, "\\"), "g"));
return m ? m.length:0;
}
Just code-golfing Rebecca Chernoff's solution :-)
alert(("This is a string.".match(/is/g) || []).length);
The non-regex version:
var string = 'This is a string',
searchFor = 'is',
count = 0,
pos = string.indexOf(searchFor);
while (pos > -1) {
++count;
pos = string.indexOf(searchFor, ++pos);
}
console.log(count); // 2
String.prototype.Count = function (find) {
return this.split(find).length - 1;
}
console.log("This is a string.".Count("is"));
This will return 2.
Here is the fastest function!
Why is it faster?
Doesn't check char by char (with 1 exception)
Uses a while and increments 1 var (the char count var) vs. a for loop checking the length and incrementing 2 vars (usually var i and a var with the char count)
Uses WAY less vars
Doesn't use regex!
Uses an (hopefully) highly optimized function
All operations are as combined as they can be, avoiding slowdowns due to multiple operations
String.prototype.timesCharExist=function(c){var t=0,l=0,c=(c+'')[0];while(l=this.indexOf(c,l)+1)++t;return t};
Here is a slower and more readable version:
String.prototype.timesCharExist = function ( chr ) {
var total = 0, last_location = 0, single_char = ( chr + '' )[0];
while( last_location = this.indexOf( single_char, last_location ) + 1 )
{
total = total + 1;
}
return total;
};
This one is slower because of the counter, long var names and misuse of 1 var.
To use it, you simply do this:
'The char "a" only shows up twice'.timesCharExist('a');
Edit: (2013/12/16)
DON'T use with Opera 12.16 or older! it will take almost 2.5x more than the regex solution!
On chrome, this solution will take between 14ms and 20ms for 1,000,000 characters.
The regex solution takes 11-14ms for the same amount.
Using a function (outside String.prototype) will take about 10-13ms.
Here is the code used:
String.prototype.timesCharExist=function(c){var t=0,l=0,c=(c+'')[0];while(l=this.indexOf(c,l)+1)++t;return t};
var x=Array(100001).join('1234567890');
console.time('proto');x.timesCharExist('1');console.timeEnd('proto');
console.time('regex');x.match(/1/g).length;console.timeEnd('regex');
var timesCharExist=function(x,c){var t=0,l=0,c=(c+'')[0];while(l=x.indexOf(c,l)+1)++t;return t;};
console.time('func');timesCharExist(x,'1');console.timeEnd('func');
The result of all the solutions should be 100,000!
Note: if you want this function to count more than 1 char, change where is c=(c+'')[0] into c=c+''
var temp = "This is a string.";
console.log((temp.match(new RegExp("is", "g")) || []).length);
A simple way would be to split the string on the required word, the word for which we want to calculate the number of occurences, and subtract 1 from the number of parts:
function checkOccurences(string, word) {
return string.split(word).length - 1;
}
const text="Let us see. see above, see below, see forward, see backward, see left, see right until we will be right";
const count=countOccurences(text,"see "); // 2
I think the purpose for regex is much different from indexOf.
indexOf simply find the occurance of a certain string while in regex you can use wildcards like [A-Z] which means it will find any capital character in the word without stating the actual character.
Example:
var index = "This is a string".indexOf("is");
console.log(index);
var length = "This is a string".match(/[a-z]/g).length;
// where [a-z] is a regex wildcard expression thats why its slower
console.log(length);
Super duper old, but I needed to do something like this today and only thought to check SO afterwards. Works pretty fast for me.
String.prototype.count = function(substr,start,overlap) {
overlap = overlap || false;
start = start || 0;
var count = 0,
offset = overlap ? 1 : substr.length;
while((start = this.indexOf(substr, start) + offset) !== (offset - 1))
++count;
return count;
};
var myString = "This is a string.";
var foundAtPosition = 0;
var Count = 0;
while (foundAtPosition != -1)
{
foundAtPosition = myString.indexOf("is",foundAtPosition);
if (foundAtPosition != -1)
{
Count++;
foundAtPosition++;
}
}
document.write("There are " + Count + " occurrences of the word IS");
Refer :- count a substring appears in the string for step by step explanation.
Building upon #Vittim.us answer above. I like the control his method gives me, making it easy to extend, but I needed to add case insensitivity and limit matches to whole words with support for punctuation. (e.g. "bath" is in "take a bath." but not "bathing")
The punctuation regex came from: https://stackoverflow.com/a/25575009/497745 (How can I strip all punctuation from a string in JavaScript using regex?)
function keywordOccurrences(string, subString, allowOverlapping, caseInsensitive, wholeWord)
{
string += "";
subString += "";
if (subString.length <= 0) return (string.length + 1); //deal with empty strings
if(caseInsensitive)
{
string = string.toLowerCase();
subString = subString.toLowerCase();
}
var n = 0,
pos = 0,
step = allowOverlapping ? 1 : subString.length,
stringLength = string.length,
subStringLength = subString.length;
while (true)
{
pos = string.indexOf(subString, pos);
if (pos >= 0)
{
var matchPos = pos;
pos += step; //slide forward the position pointer no matter what
if(wholeWord) //only whole word matches are desired
{
if(matchPos > 0) //if the string is not at the very beginning we need to check if the previous character is whitespace
{
if(!/[\s\u2000-\u206F\u2E00-\u2E7F\\'!"#$%&\(\)*+,\-.\/:;<=>?#\[\]^_`{|}~]/.test(string[matchPos - 1])) //ignore punctuation
{
continue; //then this is not a match
}
}
var matchEnd = matchPos + subStringLength;
if(matchEnd < stringLength - 1)
{
if (!/[\s\u2000-\u206F\u2E00-\u2E7F\\'!"#$%&\(\)*+,\-.\/:;<=>?#\[\]^_`{|}~]/.test(string[matchEnd])) //ignore punctuation
{
continue; //then this is not a match
}
}
}
++n;
} else break;
}
return n;
}
Please feel free to modify and refactor this answer if you spot bugs or improvements.
For anyone that finds this thread in the future, note that the accepted answer will not always return the correct value if you generalize it, since it will choke on regex operators like $ and .. Here's a better version, that can handle any needle:
function occurrences (haystack, needle) {
var _needle = needle
.replace(/\[/g, '\\[')
.replace(/\]/g, '\\]')
return (
haystack.match(new RegExp('[' + _needle + ']', 'g')) || []
).length
}
Try it
<?php
$str = "33,33,56,89,56,56";
echo substr_count($str, '56');
?>
<script type="text/javascript">
var temp = "33,33,56,89,56,56";
var count = temp.match(/56/g);
alert(count.length);
</script>
Simple version without regex:
var temp = "This is a string.";
var count = (temp.split('is').length - 1);
alert(count);
No one will ever see this, but it's good to bring back recursion and arrow functions once in a while (pun gloriously intended)
String.prototype.occurrencesOf = function(s, i) {
return (n => (n === -1) ? 0 : 1 + this.occurrencesOf(s, n + 1))(this.indexOf(s, (i || 0)));
};
function substrCount( str, x ) {
let count = -1, pos = 0;
do {
pos = str.indexOf( x, pos ) + 1;
count++;
} while( pos > 0 );
return count;
}
ES2020 offers a new MatchAll which might be of use in this particular context.
Here we create a new RegExp, please ensure you pass 'g' into the function.
Convert the result using Array.from and count the length, which returns 2 as per the original requestor's desired output.
let strToCheck = RegExp('is', 'g')
let matchesReg = "This is a string.".matchAll(strToCheck)
console.log(Array.from(matchesReg).length) // 2
Now this is a very old thread i've come across but as many have pushed their answer's, here is mine in a hope to help someone with this simple code.
var search_value = "This is a dummy sentence!";
var letter = 'a'; /*Can take any letter, have put in a var if anyone wants to use this variable dynamically*/
letter = letter && "string" === typeof letter ? letter : "";
var count;
for (var i = count = 0; i < search_value.length; count += (search_value[i++] == letter));
console.log(count);
I'm not sure if it is the fastest solution but i preferred it for simplicity and for not using regex (i just don't like using them!)
You could try this
let count = s.length - s.replace(/is/g, "").length;
We can use the js split function, and it's length minus 1 will be the number of occurrences.
var temp = "This is a string.";
alert(temp.split('is').length-1);
Here is my solution. I hope it would help someone
const countOccurence = (string, char) => {
const chars = string.match(new RegExp(char, 'g')).length
return chars;
}
var countInstances = function(body, target) {
var globalcounter = 0;
var concatstring = '';
for(var i=0,j=target.length;i<body.length;i++){
concatstring = body.substring(i-1,j);
if(concatstring === target){
globalcounter += 1;
concatstring = '';
}
}
return globalcounter;
};
console.log( countInstances('abcabc', 'abc') ); // ==> 2
console.log( countInstances('ababa', 'aba') ); // ==> 2
console.log( countInstances('aaabbb', 'ab') ); // ==> 1
substr_count translated to Javascript from php
Locutus (Package that translates Php to JS)
substr_count (official page, code copied below)
function substr_count (haystack, needle, offset, length) {
// eslint-disable-line camelcase
// discuss at: https://locutus.io/php/substr_count/
// original by: Kevin van Zonneveld (https://kvz.io)
// bugfixed by: Onno Marsman (https://twitter.com/onnomarsman)
// improved by: Brett Zamir (https://brett-zamir.me)
// improved by: Thomas
// example 1: substr_count('Kevin van Zonneveld', 'e')
// returns 1: 3
// example 2: substr_count('Kevin van Zonneveld', 'K', 1)
// returns 2: 0
// example 3: substr_count('Kevin van Zonneveld', 'Z', 0, 10)
// returns 3: false
var cnt = 0
haystack += ''
needle += ''
if (isNaN(offset)) {
offset = 0
}
if (isNaN(length)) {
length = 0
}
if (needle.length === 0) {
return false
}
offset--
while ((offset = haystack.indexOf(needle, offset + 1)) !== -1) {
if (length > 0 && (offset + needle.length) > length) {
return false
}
cnt++
}
return cnt
}
Check out Locutus's Translation Of Php's substr_count function
The parameters:
ustring: the superset string
countChar: the substring
A function to count substring occurrence in JavaScript:
function subStringCount(ustring, countChar){
var correspCount = 0;
var corresp = false;
var amount = 0;
var prevChar = null;
for(var i=0; i!=ustring.length; i++){
if(ustring.charAt(i) == countChar.charAt(0) && corresp == false){
corresp = true;
correspCount += 1;
if(correspCount == countChar.length){
amount+=1;
corresp = false;
correspCount = 0;
}
prevChar = 1;
}
else if(ustring.charAt(i) == countChar.charAt(prevChar) && corresp == true){
correspCount += 1;
if(correspCount == countChar.length){
amount+=1;
corresp = false;
correspCount = 0;
prevChar = null;
}else{
prevChar += 1 ;
}
}else{
corresp = false;
correspCount = 0;
}
}
return amount;
}
console.log(subStringCount('Hello World, Hello World', 'll'));
var str = 'stackoverflow';
var arr = Array.from(str);
console.log(arr);
for (let a = 0; a <= arr.length; a++) {
var temp = arr[a];
var c = 0;
for (let b = 0; b <= arr.length; b++) {
if (temp === arr[b]) {
c++;
}
}
console.log(`the ${arr[a]} is counted for ${c}`)
}

Categories