Count the number of integers in a string - javascript

how can I count the number of integers in a string using jQuery or javascript?
For example g66ghy7 = 3

alert("g66ghy7".replace(/[^0-9]/g,"").length);
Look here.

I find this to look pretty/simple:
var count = ('1a2b3c'.match(/\d/g) || []).length
A RegExp will probably perform better (it appears):
var r = new RegExp('\\d', 'g')
, count = 0
while(r.exec('1a2b3c')) count++;

The simplest solution would be to use a regular expression to replace all but the numeric values and pull out the length afterwards. Consider the following:
var s = 'g66ghy7';
alert(s.replace(/\D/g, '').length); //3

A little longer alternative is to convert each char to a number; if it doesn't fail, raise the counter.
var sTest = "g66ghy7";
var iCount = 0;
for (iIndex in sTest) {
if (!isNaN(parseInt(sTest[iIndex]))) {
iCount++;
}
}
alert(iCount);
Also see my jsfiddle.

Short and sweet:
str.match(/\d/g)?.length || 0
Thanks to #CertainPerformance answer here
const str = 'g66ghy7'
const digitCount = str.match(/\d/g)?.length || 0;
console.log('digitCount', digitCount)

A simple for can solve this:
const value = "test:23:string236";
let totalNumbers = 0;
for (let i = 0; i < value.length; i++) {
const element = value[i];
if (isFinite(element)) {
totalNumbers++;
}
}
console.log(totalNumbers);

Related

Return initial letters of postcode in javascript

How can I get the initial letters from a postcode in javascript? I just want the letters before the numbers start, like this:
E.g - 'L159XU' would return 'L'
E.g - 'TW136PZ' would return 'TW'
I was originally doing this:
const letters = postcode.substring(0, 2);
But some only have one letter, while others have two. Is there a way to do this?
I have tested this:
HTML
<p id="test"></p>
JavaScript Regular Expressions
let text = 'TW136PZ';
let pattern = /[a-zA-Z]+|[0-9]+/g;
let result = text.match(pattern);
document.getElementById("test").innerHTML = result[0]; // return "TW"
use a split function with a regex,
let res = "TW136PZ".split(/[0-9]+/)[0] ; // TW
more about regex here
There are different valid implementations
function callX() {
return 'TW136PZ'.slice(0, 'TW136PZ'.search(/[0-9]/))
}
function callY() {
return 'TW136PZ'.split(/[0-9]+/)[0]
}
function callZ() {
return 'TW136PZ'.match( /^[a-zA-Z]+/ )[0]
}
when benchmarking these:
performance.mark("beginX");
for (let i = 0; i < 10000000; ++i) {
callX();
}
performance.mark("endX");
performance.mark("beginY");
for (let i = 0; i < 10000000; ++i) {
callY();
}
performance.mark("endY");
performance.mark("beginZ");
for (let i = 0; i < 10000000; ++i) {
callZ();
}
performance.mark("endZ");
performance.measure("X","beginX","endX");
performance.measure("Y","beginY","endY");
performance.measure("Z","beginZ","endZ");
console.log(performance.getEntriesByType("measure"))
it turns out the first implementation is the fastest, while the second implementation (using split) is the slowest.
I think this is due to not requiring to instantiate another array.
Posting a solution that does not use regular expressions, because I haven't seen one:
function parsePostcode(postcode) {
const charIsADigit = function(ch) {
const code = ch.charCodeAt(0)
return code >= 48 && 58 > code;
};
let prefix = ""
for (let i = 0; i < postcode.length; ++i) {
const ch = postcode[i]
const is_digit = charIsADigit(ch)
if (is_digit) break;
prefix += ch
}
return prefix;
}
console.log(parsePostcode("L159XU"))
console.log(parsePostcode("TW136PZ"))
const postc='TwA1234';
const letters=postc.match( /^[a-zA-Z]+/ )[0];
console.log(letters);
^ – begin of input
a-z – lowercase English Letters included
A-Z – Uppercases included
+ – one or more times it appears!
As you wanted, it returns a string of as many initial latin latters as needed, three in this case.

Javascript: converting string to an array

This is one of my function for a calculator project. First I needed to convert the input string into an array, and do the operation later. (assuming that input has only numbers and '+' sign for now.
My question here is, how do I improve this code? What are the other ways to deal with this problem? (Time complexity, cleanness, shorter code.......whatever)
function convertArray(input) {
let array = [];
let num = "";
for (let i = 0; i < input.length; i++) {
if (input.charAt(i) == '+') {
array.push(input.charAt(i));
} else {
do {
num += input.charAt(i);
i++;
} while (i < input.length && input.charAt(i) !== '+');
array.push(num);
num = "";
i--;
}
}
return array;
}
console.log(convertArray("10+2+3000+70+1"));
You could split with a group. this add the group as well to the array.
For other calculation signs, you could add them to the brackets.
const convertArray = string => string.split(/([+])/);
console.log(convertArray("10+2+3000+70+1"));
const q = prompt('Sum?');
alert('Answer: ' + eval(q));
Would not recommend using eval, but if all you need is a quick and dirty trick, it works.
Personally, I'd recommend a library such as Math.js, but any will do.
If you really need to do this by yourself for a project, I'd recommend checking out the answers here: Evaluating a string as a mathematical expression in JavaScript.
Hope you succeed in whatever you're planning on doing.
It seems the complexity must have something to do with your wish to determing operators. In your code you just push them all into the array. To do that is like
const re = /((\d+)|([^\d]+))/g
const convertArray = str => {
let match, arr=[];
while (match = re.exec(str)) {
arr.push(match[1]) // here you can determine if you have an operator
console.log(match[1],"Operator?",!/^\d+$/.test(match[1]))
}
return arr
}
const str = "10+2+3000+70+1";
console.log(convertArray(str));

JS: Reversing a string using nested loop does not work

I have written a function called reverseStr that takes in a string as a parameter and returns the string but with the characters in reverse.
For example: reverseStr('bootcamp'); => 'pmactoob'
Following is my program:
function reverseStr(str)
{
var splitStr = str.split("");
console.log(splitStr);
var reverseString = [];
for(var i = 0; i <= splitStr.length -1 ; i++)
{
for(var j = splitStr.length - 1; j >= 0; j--)
{
reverseString[i] = splitStr[j]
}
}
return reverseString.toString().replace(/[&\/\\#,+()$~%.'":*?<>{}]/g, '');
}
If I run the function reverseStr("bootcamp") it returns bbbbbbbb.
Does anyone see a problem with the code?
Note: I DONOT WANT TO USE REVERSE() BUILT-IN FUNCTION
However, I found success with the following code but still need an answer to my initial question
function reverseStr(str)
{
var splitStr = str.split("");
reverseStr = "";
for(var i = splitStr.length - 1; i >= 0 ; i = i - 1)
{
reverseStr += splitStr[i];
}
return reverseStr;
}
You don't need to double-iterate through the characters, i.e., do not need to nest for loops. Iterate once and grab the chars in reverse order, like this:
function reverseStr(str)
{
var splitStr = str.split("");
console.log(splitStr);
var reverseString = [];
for(var i = 0, j=splitStr.length-1; i <= splitStr.length -1 ; i++, j--)
{
reverseString[i] = splitStr[j]
}
return reverseString.toString().replace(/[&\/\\#,+()$~%.'":*?<>{}]/g, '');
}
You can see that here the loop goes on for as long as i <= splitStr.length -1,ie, length of the string. This is sufficient to get the mirroring character (i versus Array.length-i).
Here is a working snippet to demo:
var reverseStr = function(str) {
let result = String();
for(let i = str.length-1; i >= 0; i--) {
result += str.charAt(i);
}
return result.replace(/[&\/\\#,+()$~%.'":*?<>{}]/g, '');
}
$('button').click(function() {
$('.result').text(reverseStr($('#str').val()));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="str">
<button>Reverse it</button>
<div class="result"></div>
Perhaps a more elegant way to achieve the same (apart from Array.prototype.reverse()) would be to use String.prototype.chatAt(). This would avoid two conversions to and from an array, and also save you one variable. Granted, the code is much shorter and more obvious in what it is doing.
var reverseStr = function(str) {
let result = String(); // An empty string to store the result
for(let i = str.length-1; i >= 0; i--) { // Iterate backwards thru the chars and add to the result string
result += str.charAt(i);
}
return result.replace(/[&\/\\#,+()$~%.'":*?<>{}]/g, ''); // Original return method of the author
}
$('button').click(function() {
$('.result').text(reverseStr($('#str').val()));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="str">
<button>Reverse it</button>
<div class="result"></div>
The problem is that your nested for loop runs its whole course before it returns to the outer for loop. So, it just repeats one character the amount of times equal to the length. Instead of having another for loop, just add a simple counter for j like j++ inside your outer for loop and use that value with the i value.
To the original poster, consider this:
If you know the length of the original string, you therefore know the offset of that last position within the original string.
Iterate through the original string in reverse order, appending the current position's value to a new string. The new string would be the reverse of the original.
Aydin's example is essentially correct. Here's my very similar version, with comments:
function reverseString(inputString) {
// create a new empty string
var newString = "";
// iterate through the characters of the string in reverse order,
// appending to the new string
for (var i = inputString.length - 1; i >= 0; i--) {
newString += inputString[i];
}
return newString;
}
console.log(reverseString('bootcamp'));

How to format number to currency?

I currently doing formatting of number to currency but is not working on a collection of an array. I used javascript to use the Math.round function. I would like to know how properly use this function. I appreciate your suggestion. Thank you.
Array:
{
"data": [
[
"9812355000",
"23397000",
"13976000"
]
]
}
for (var x = 0; x < data.data.length; x++) {
for (var i0 = 0; i0 < data.data[x].length; i0++) {
dynamicColumn += `<td>${data.data[x][i0] === null || data.data[x][i0] === ""
? 0
: Math.round(data.data[x][i0])}</td>`;
}
}
Need to achieve:
9,812,355,000
23,397,000
13,976,000
To achieve the output you specified using your array, you can iterate though the digits backwards (meaning, starting from the last number and moving to the first number) and then inserting a comma after 3 digits. Some sample code could look like this:
for(let i = numberString.length - 1; i >= 0; i--) {
if (i % 3 === 0)
array.insert(i, ','); // this is not a real function. I leave it up to you to implement this. first param is index and second is what to insert
}
var thousandSeparationRegexp = /\B(?=(\d{3})+(?!\d))/g;
// iterate through numbers
var numberString = number.toString();
var formatted = numberString.replace(thousandSeparationRegexp, ',');
Or inline:
var formatted = number.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
You can use an Intl.NumberFormat().format(x):
function myFunction() {
var x = document.getElementById("value_unformated").value
var a = Intl.NumberFormat().format(x)
var text = "Currency format: " + a + "<br>";
document.getElementById("value_formated").innerHTML = text;
}
<input type="number" id="value_unformated" value="13528468">
<button onclick="myFunction()">Format</button>
<p id="value_formated"></p>

convert digital display format

quick question, I have some integrate variable in javascript, say: 123456, or 123456789, it can be any valid number. Now, I would like to convert the number to a string like "123,456" or "123,456,789". Does anyone have a good algorithm for this? Of course, it should work for any numbers. For example: for 2000 ---> 2,000; 123456--->123,456
Give this a shot.
var num = 12345678;
var str = num + ""; // cast to string
var out = [];
for (var i = str.length - 3; i > 0; i -= 3) {
out.unshift(str.substr(i, 3));
}
out.unshift(str.substr(0, 3 + i));
out = out.join(','); // "12,345,678"
in addition to the other excellent solution
var n = 999999
var s = n.toLocaleString()

Categories