Related
I have a text box that will have a currency string in it that I then need to convert that string to a double to perform some operations on it.
"$1,100.00" → 1100.00
This needs to occur all client side. I have no choice but to leave the currency string as a currency string as input but need to cast/convert it to a double to allow some mathematical operations.
Remove all non dot / digits:
var currency = "-$4,400.50";
var number = Number(currency.replace(/[^0-9.-]+/g,""));
accounting.js is the way to go. I used it at a project and had very good experience using it.
accounting.formatMoney(4999.99, "€", 2, ".", ","); // €4.999,99
accounting.unformat("€ 1.000.000,00", ","); // 1000000
You can find it at GitHub
Use a regex to remove the formating (dollar and comma), and use parseFloat to convert the string to a floating point number.`
var currency = "$1,100.00";
currency.replace(/[$,]+/g,"");
var result = parseFloat(currency) + .05;
I know this is an old question but wanted to give an additional option.
The jQuery Globalize gives the ability to parse a culture specific format to a float.
https://github.com/jquery/globalize
Given a string "$13,042.00", and Globalize set to en-US:
Globalize.culture("en-US");
You can parse the float value out like so:
var result = Globalize.parseFloat(Globalize.format("$13,042.00", "c"));
This will give you:
13042.00
And allows you to work with other cultures.
I know this is an old question, but CMS's answer seems to have one tiny little flaw: it only works if currency format uses "." as decimal separator.
For example, if you need to work with russian rubles, the string will look like this:
"1 000,00 rub."
My solution is far less elegant than CMS's, but it should do the trick.
var currency = "1 000,00 rub."; //it works for US-style currency strings as well
var cur_re = /\D*(\d+|\d.*?\d)(?:\D+(\d{2}))?\D*$/;
var parts = cur_re.exec(currency);
var number = parseFloat(parts[1].replace(/\D/,'')+'.'+(parts[2]?parts[2]:'00'));
console.log(number.toFixed(2));
Assumptions:
currency value uses decimal notation
there are no digits in the string that are not a part of the currency value
currency value contains either 0 or 2 digits in its fractional part *
The regexp can even handle something like "1,999 dollars and 99 cents", though it isn't an intended feature and it should not be relied upon.
Hope this will help someone.
This example run ok
var currency = "$1,123,456.00";
var number = Number(currency.replace(/[^0-9\.]+/g,""));
console.log(number);
For anyone looking for a solution in 2021 you can use Currency.js.
After much research this was the most reliable method I found for production, I didn't have any issues so far. In addition it's very active on Github.
currency(123); // 123.00
currency(1.23); // 1.23
currency("1.23") // 1.23
currency("$12.30") // 12.30
var value = currency("123.45");
currency(value); // 123.45
typescript
import currency from "currency.js";
currency("$12.30").value; // 12.30
This is my function. Works with all currencies..
function toFloat(num) {
dotPos = num.indexOf('.');
commaPos = num.indexOf(',');
if (dotPos < 0)
dotPos = 0;
if (commaPos < 0)
commaPos = 0;
if ((dotPos > commaPos) && dotPos)
sep = dotPos;
else {
if ((commaPos > dotPos) && commaPos)
sep = commaPos;
else
sep = false;
}
if (sep == false)
return parseFloat(num.replace(/[^\d]/g, ""));
return parseFloat(
num.substr(0, sep).replace(/[^\d]/g, "") + '.' +
num.substr(sep+1, num.length).replace(/[^0-9]/, "")
);
}
Usage : toFloat("$1,100.00") or toFloat("1,100.00$")
// "10.000.500,61 TL" price_to_number => 10000500.61
// "10000500.62" number_to_price => 10.000.500,62
JS FIDDLE: https://jsfiddle.net/Limitlessisa/oxhgd32c/
var price="10.000.500,61 TL";
document.getElementById("demo1").innerHTML = price_to_number(price);
var numberPrice="10000500.62";
document.getElementById("demo2").innerHTML = number_to_price(numberPrice);
function price_to_number(v){
if(!v){return 0;}
v=v.split('.').join('');
v=v.split(',').join('.');
return Number(v.replace(/[^0-9.]/g, ""));
}
function number_to_price(v){
if(v==0){return '0,00';}
v=parseFloat(v);
v=v.toFixed(2).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
v=v.split('.').join('*').split(',').join('.').split('*').join(',');
return v;
}
You can try this
var str = "$1,112.12";
str = str.replace(",", "");
str = str.replace("$", "");
console.log(parseFloat(str));
let thousands_seps = '.';
let decimal_sep = ',';
let sanitizeValue = "R$ 2.530,55".replace(thousands_seps,'')
.replace(decimal_sep,'.')
.replace(/[^0-9.-]+/, '');
// Converting to float
// Result 2530.55
let stringToFloat = parseFloat(sanitizeValue);
// Formatting for currency: "R$ 2.530,55"
// BRL in this case
let floatTocurrency = Number(stringToFloat).toLocaleString('pt-BR', {style: 'currency', currency: 'BRL'});
// Output
console.log(stringToFloat, floatTocurrency);
I know you've found a solution to your question, I just wanted to recommend that maybe you look at the following more extensive jQuery plugin for International Number Formats:
International Number Formatter
How about simply
Number(currency.replace(/[^0-9-]+/g,""))/100;
Works with all currencies and locales. replaces all non-numeric chars (you can have €50.000,00 or $50,000.00) input must have 2 decimal places
jQuery.preferCulture("en-IN");
var price = jQuery.format(39.00, "c");
output is: Rs. 39.00
use jquery.glob.js,
jQuery.glob.all.js
Here's a simple function -
function getNumberFromCurrency(currency) {
return Number(currency.replace(/[$,]/g,''))
}
console.log(getNumberFromCurrency('$1,000,000.99')) // 1000000.99
For currencies that use the ',' separator mentioned by Quethzel Diaz
Currency is in Brazilian.
var currency_br = "R$ 1.343,45";
currency_br = currency_br.replace('.', "").replace(',', '.');
var number_formated = Number(currency_br.replace(/[^0-9.-]+/g,""));
var parseCurrency = function (e) {
if (typeof (e) === 'number') return e;
if (typeof (e) === 'string') {
var str = e.trim();
var value = Number(e.replace(/[^0-9.-]+/g, ""));
return str.startsWith('(') && str.endsWith(')') ? -value: value;
}
return e;
}
This worked for me and covers most edge cases :)
function toFloat(num) {
const cleanStr = String(num).replace(/[^0-9.,]/g, '');
let dotPos = cleanStr.indexOf('.');
let commaPos = cleanStr.indexOf(',');
if (dotPos < 0) dotPos = 0;
if (commaPos < 0) commaPos = 0;
const dotSplit = cleanStr.split('.');
const commaSplit = cleanStr.split(',');
const isDecimalDot = dotPos
&& (
(commaPos && dotPos > commaPos)
|| (!commaPos && dotSplit[dotSplit.length - 1].length === 2)
);
const isDecimalComma = commaPos
&& (
(dotPos && dotPos < commaPos)
|| (!dotPos && commaSplit[commaSplit.length - 1].length === 2)
);
let integerPart = cleanStr;
let decimalPart = '0';
if (isDecimalComma) {
integerPart = commaSplit[0];
decimalPart = commaSplit[1];
}
if (isDecimalDot) {
integerPart = dotSplit[0];
decimalPart = dotSplit[1];
}
return parseFloat(
`${integerPart.replace(/[^0-9]/g, '')}.${decimalPart.replace(/[^0-9]/g, '')}`,
);
}
toFloat('USD 1,500.00'); // 1500
toFloat('USD 1,500'); // 1500
toFloat('USD 500.00'); // 500
toFloat('USD 500'); // 500
toFloat('EUR 1.500,00'); // 1500
toFloat('EUR 1.500'); // 1500
toFloat('EUR 500,00'); // 500
toFloat('EUR 500'); // 500
Such a headache and so less consideration to other cultures for nothing...
here it is folks:
let floatPrice = parseFloat(price.replace(/(,|\.)([0-9]{3})/g,'$2').replace(/(,|\.)/,'.'));
as simple as that.
$ 150.00
Fr. 150.00
€ 689.00
I have tested for above three currency symbols .You can do it for others also.
var price = Fr. 150.00;
var priceFloat = price.replace(/[^\d\.]/g, '');
Above regular expression will remove everything that is not a digit or a period.So You can get the string without currency symbol but in case of " Fr. 150.00 " if you console for output then you will get price as
console.log('priceFloat : '+priceFloat);
output will be like priceFloat : .150.00
which is wrong so you check the index of "." then split that and get the proper result.
if (priceFloat.indexOf('.') == 0) {
priceFloat = parseFloat(priceFloat.split('.')[1]);
}else{
priceFloat = parseFloat(priceFloat);
}
function NumberConvertToDecimal (number) {
if (number == 0) {
return '0.00';
}
number = parseFloat(number);
number = number.toFixed(2).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1");
number = number.split('.').join('*').split('*').join('.');
return number;
}
This function should work whichever the locale and currency settings :
function getNumPrice(price, decimalpoint) {
var p = price.split(decimalpoint);
for (var i=0;i<p.length;i++) p[i] = p[i].replace(/\D/g,'');
return p.join('.');
}
This assumes you know the decimal point character (in my case the locale is set from PHP, so I get it with <?php echo cms_function_to_get_decimal_point(); ?>).
You should be able to handle this using vanilla JS. The Internationalization API is part of JS core: ECMAScript Internationalization API
https://www.w3.org/International/wiki/JavaScriptInternationalization
This answer worked for me: How to format numbers as currency strings
The following function works perfect, but when the amount over 1 million, the function don't work exactly.
Example:
AMOUNTPAID = 35555
The output is: 35.555,00 - work fine
But when the amount paid is for example: 1223578 (over 1 Million),
is the output the following output value: 1.223.235,00 (but it must be: 1.223.578,00) - there is a deviation of 343
Any ideas?
I call the function via HTML as follows:
<td class="tr1 td2"><p class="p2 ft4"><script type="text/javascript">document.write(ConvertBetrag('{{NETAMOUNT}}'))</script> €</P></TD>
#
Here ist the Javascript:
function Convertamount( amount ){
var number = amount;
number = Math.round(number * Math.pow(12, 2)) / Math.pow(12, 2);
number = number.toFixed(2);
number = number.toString();
var negative = false;
if (number.indexOf("-") == 0)
{
negative = true ;
number = number.replace("-","");
}
var str = number.toString();
str = str.replace(".", ",");
// number before decimal point
var intbeforedecimaln = str.length - (str.length - str.indexOf(","));
// number of delimiters
var intKTrenner = Math.floor((intbeforedecimaln - 1) / 3);
// Leading digits before the first dot
var intZiffern = (intbeforedecimaln % 3 == 0) ? 3 : (intbeforedecimaln % 3);
// Provided digits before the first thousand separator with point
strNew = str.substring(0, intZiffern);
// Auxiliary string without the previously treated digits
strHelp = str.substr(intZiffern, (str.length - intZiffern));
// Through thousands of remaining ...
for(var i=0; i<intKTrenner; i++)
{
// attach 3 digits of the nearest thousand group point to String
strNew += "." + strHelp.substring(0, 3);
// Post new auxiliary string without the 3 digits being treated
strHelp = strHelp.substr(intZiffern, (strHelp.length - intZiffern));
}
// attach a decimal
var szdecimal = str.substring(intbeforedecimaln, str.length);
if (szdecimal.length < 3 )
{
strNew += str.substring(intbeforedecimaln, str.length) + '0';
}
else
{
strNew += str.substring(intbeforedecimaln, str.length);
}
var number = strNew;
if (negative)
{
number = "- " + number ;
}
return number;
}
JavaScript's Math functions have a toLocaleString method. Why don't you just use this?
var n = (1223578.00).toLocaleString();
-> "1,223,578.00"
The locale you wish to use can be passed in as a parameter, for instance:
var n = (1223578.00).toLocaleString('de-DE');
-> "1.223.578,00"
function convertToValidPhoneNumber(text) {
var result = [];
text = text.replace(/^\d{2}-?\d{3}-?\d{3}-?\d{3}$/, "");
while (text.length >= 6){
result.push(text.substring(0, 3));
text = text.substring(3);
}
if (text.length > 0) result.push(text);
return result.join("-");
}
I test this function against 35200123456785 input string.
It gives me like a number like 352-001-234-56785 but I want 35200-12345678-5.
What do I need to do to fix this?
You can use this updated function that uses ^(?=[0-9]{11})([0-9]{5})([0-9]{8})([0-9])$ regex:
^ - String start
(?=[0-9]{11}) - Ensures there are 11 digits in the phone number
([0-9]{5}) - First group capturing 5 digits
([0-9]{8}) - Second group capturing 8 digits
([0-9]) - Third group capturing 1 digit
$ - String end
Replacement string - "$1-$2-$3" - uses back-references to those capturing groups in the regex by numbers and adds hyphens where you need them to be.
In case you have hyphens inside the input string, you should remove them before.
function convertToValidPhoneNumber(text) {
return text = text.replace(/-/g,"").replace(/^(?=[0-9]{11})([0-9]{5})([0-9]{8})([0-9])$/, "$1-$2-$3");
}
document.getElementById("res").innerHTML = convertToValidPhoneNumber("35200123456785") + " and " + convertToValidPhoneNumber("35-200-123-456-785");
<div id="res"/>
number = this.state.number;
var expression = /(\D+)/g;
var npa = "";
var nxx = "";
var last4 = "";
number = number.toString().replace(expression, "");
npa = number.substr(0, 3);
nxx = number.substr(3, 3);
last4 = number.substr(6, 4);
number = npa + "-" + nxx + "-" + last4
Basically, I have a string of unknown numbers (determined by user input + my own math), and I need to split this string into 3 parts.
For example, I may have "1273498". I need to split it at the two characters, and the 3rd and 4th from the RIGHT, like so:
127
34
98
Another example: 1234567890 would need to be:
123456
78
90
Currently, I am accomplishing it this way:
// get first input box value
var depositgold = document.getElementById('v-gold').value;
// set it to 0 if it's empty
if(depositgold == null || depositgold == '')
depositgold = 0;
// second input box value
var depositsilver = document.getElementById('v-silver').value;
if(depositsilver == null || depositsilver == '')
depositsilver = 0;
// third input box value
var depositcopper = document.getElementById('v-copper').value;
if(depositcopper == null || depositcopper == '')
depositcopper = 0;
// combine the 3 input box values (adding dec to make split easier)
var depositnums = depositgold + '.' + depositsilver + depositcopper;
// do some math on our new value, then split it at out dec
var deposit12 = (0.15 * depositnums).toFixed(4).split(".");
// split the last part of the above split into 4 characters
var result12 = deposit12[1].split("", 3);
// keep the first part of out dec split
var deposit12gold = deposit12[0];
// combine the second part split results into paired numbers
var deposit12silver = result12[0] + result12[1];
var deposit12copper = result12[2] + result12[3];
// repeat the above process
var deposit24 = (0.30 * depositnums).toFixed(4).split(".");
var result24 = deposit24[1].split("", 3);
var deposit24gold = deposit24[0];
var deposit24silver = result24[0] + result24[1];
var deposit24copper = result24[2] + result24[3];
var deposit48 = (0.60 * depositnums).toFixed(4).split(".");
var result48 = deposit48[1].split("", 3);
var deposit48gold = deposit48[0];
var deposit48silver = result48[0] + result48[1];
var deposit48copper = result48[2] + result48[3];
I know there must be a much better (and more sane) way of accomplishing the above - I need to do it several more times for this project, and I'm certainly not looking forward to continuing to do it this way.
I am new to JS and programming, so laugh away, just try not to laugh too hard ;)
Try something along these lines:
var str = "123412341";
var matches = str.match(/(.+?)?(.{2})?(.{2})?$/);
// matches[1] = 12341
// matches[2] = 23
// matches[3] = 41
You may want to modify the RegEx depending on your input, currently all groups are optional.
Just use the substring method
var number = 123456789;
var one = number.substring( 0, number.length - 4 );
var two = number.substring( number.length -4, number.length - 2);
var three = number.substring( number.length - 2 );
Use the substr() method for this:
var L = mystring.length
var part1 = mystring.substr(0,L-4);
var part2 = mystring.substr(L-4,2);
var part3 = mystring.substr(L-2,2);
('1234'+'56'+'78').match(/(\d*)(\d\d)(\d\d)/)
["12345678", "1234", "56", "78"]
var number = 1234567890;
number = number.toString();
var a = number.substr(0, number.length - 4),
b = number.substr(-2),
c = number.substr(number.length - 4, 2);
console.log(a, b, c);
jsFiddle.
Output
123456 90 78
here is a function i made:
/**
* #param num A number to split like 382203849238
* #return Returns an array of size 3, where index 0 = 38220384, index 1 = 92, index 2 = 38 based on the example above
*/
function splitNumbers(num) {
var num = (typeof num == 'string' || typeof num == 'String') ? parseInt(num) : num,
rem = num % 10000;
return [Math.floor(num / 10000), Math.floor(rem / 100), rem % 100];
}
// Function to parse code in 3 parts
function parse_code_Split (code)
{
var len = code.length;
var divisor = (len / 3) >> 0; // get whole number
console.log(divisor);
var stringReg = "";
var regexp = ".{1," + divisor + "}";
try{
stringReg = new RegExp(regexp,"g");
}catch(Error){
window.console.log(Error.message);
}
codeSplit = code.match(stringReg);
// window.console.log(" codeSplit[0] " + codeSplit[0]);
// window.console.log(" codeSplit[1] " + codeSplit[1]);
// window.console.log(" codeSplit[2] " + codeSplit[2]);
// window.console.log(" codeSplit[3] " + codeSplit[3]); // remainder
return codeSplit;
}
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}`)
}