Count number of times a character appears in string [duplicate] - javascript

This question already has answers here:
Count number of occurrences for each char in a string
(23 answers)
Closed 6 years ago.
So basically I need a script that summarizes which characters and the number of times they appear in a random string. Caps have to be ignored, for example:
var myString = promt ("Type anything: "); //"hello Hello";
The end result has to be something like this: h = 2, e = 2, l = 4, o = 2 printed in the HTML document.
I've tried using myString.match().length without much success. My main problem is defining which characters to check and not checking characters twice (for example: if there are two "h" in the string not checking them twice).

You can use temporary object
var o = {};
"hello Hello".toLowerCase()
.replace(/\s+/, '')
.split('')
.forEach(e => o[e] = ++o[e] || 1);
document.write(JSON.stringify(o));
This solution uses arrow function (ES2015 standard) that doesn't work in old browsers.

var str = 'hello Hello';
var count = {};
str.split('').forEach(function(v) {
if (v === ' ') return;
v = v.toLowerCase();
count[v] = count[v] ? count[v] + 1 : 1;
})
console.log(count);

Related

Javascript replace regex using [duplicate]

This question already has answers here:
Removing Numbers from a String using Javascript
(2 answers)
Closed 3 years ago.
I need to change #x ( x a number) to x.
How can I do that, I don't know js regex..
You can try like this.
var n = Number(s.replace(/\D+/, ''))
> var s = "#123";
undefined
>
> var n = s.replace(/\D+/, '')
undefined
>
> n
'123'
>
> n = Number(n)
123
>
> n + 7
130
>
Just use replace like so:
const str = "#1235";
const num = str.replace("#", "");
console.log(num);
You can use inbuilt replace function for this purpose, which can take both, literals and regex pattern as parameter.
var str = "#12345";
str.replace("#", "");
We can also use patterns in the replace parameter, if you have multiple values to be replaced.
var str = "#123#45";
str.replace(/[##]/,"") // prints "123#45" => removes firs occurrence only
str.replace(/[##]/g,"") // prints "12345"
str.replace(/\D/,"") // prints "123#45" => removes any non-digit, first occurrence
str.replace(/\D/g,"") // prints "12345" => removes any non-digit, all occurrence
g stands for global search
[##] stands for either # or #, you can add anything here
\D stands for anything other than digits

String.split with regexp bug [duplicate]

This question already has answers here:
Why do regex constructors need to be double escaped?
(5 answers)
Closed 4 years ago.
I want to split a string by a variable number of successive characters
splitBy4('XXXXXXXX') => ['XXXX', 'XXXX']
Before injecting the variable it worked all fine :
console.log('XXXXXXXX'.split(/(\w{4})/).filter(Boolean));
// outputs : ['XXXX', 'XXXX']
console.log('XXXXXXXX'.split(new RegExp(/(\w{4})/)).filter(Boolean));
// outputs : ['XXXX', 'XXXX']
But when I try to use the RegExp class + string representation (to inject my parameter), it fails :
console.log('XXXXXXXX'.split(new RegExp('(\w{4})')).filter(Boolean));
// outputs ['XXXXXXXX']
const nb = 4;
console.log('XXXXXXXX'.split(new RegExp('(\w{'+ nb +'})')).filter(Boolean));
// outputs ['XXXXXXXX']
What am I missing and how can I inject my parameter ?
Thanks
const nb = "4";
var myRegex = new RegExp('(\\w{' + nb + '})', 'g');
var myArray = myRegex.exec('XXXXXXXX');
console.log(myArray.toString());

How to replace the second occurrence of a string in javascript [duplicate]

This question already has answers here:
Simple Javascript Replace not working [duplicate]
(3 answers)
Closed 5 years ago.
I am trying to replace the second occurrence of a string in javascript. I'm using a regex to detect all the matches of the character that I'm looking for. The alert returns the same initial text.
text = 'BLABLA';
//var count = (texte.match(/B/g) || []).length;
var t=0;
texte.replace(/B/g, function (match) {
t++;
return (t === 2) ? "Z" : match;
});
alert(text);
https://js.do/code/157264
It's because you never use the result returned by the replace function.
Here's the corrected code:
const text = 'BLABLA'
let t = 0
const result = text.replace(/B/g, match => ++t === 2 ? 'Z' : match)
console.log(result)

JS get the last dot of a string and return the string after it [duplicate]

This question already has answers here:
String manipulation - getting value after the last position of a char
(8 answers)
Closed 5 years ago.
I have this RegExp below working. But the return is True or False. What I want here is to get the last DOT of a string and return the last string after the DOT. As example below I have image.jpeg.jpeg I want to return the last jpeg. I also try g.match(x) but it gives me an error. g.match is not a function
var x = "image.jpeg.jpeg"
var g = /(.*)\.(.+)/;
alert(g.test(x));
Alternatively, you can use split method like so:
var x = "image.jpeg.jpeg";
var ans = x.split('.').pop();
console.log(ans);
Try this:
var x = "image.jpeg.jpeg"
var g = /(.*)\.(.+)/;
alert(x.match(g)[2]);
match is a method of String (not RegExp), it's argiment RegExp
Try this:
var matches = x.match(g);
if (matches.length === 0) {
console.log('Error');
return;
}
var last = m[m.length - 1]
alert(last);
use this:
var x = "image.jpeg.jpeg"
var g = /\.([0-9a-z]+)$/i;
console.log(x.match(g)[0]); //with a dot
console.log(x.match(g)[1]); //extension only

How can I parse a string and split it into two parts at a special character with javascript? [duplicate]

This question already has answers here:
How do I split a string, breaking at a particular character?
(17 answers)
Closed 8 years ago.
How can I take a string and split it at a special character into two new variables (and remove the special chars) with javascript?
For example take:
var X = Peggy Sue - Teacher
and turn it into:
varnew1 = Peggy Sue
varnew2 = Teacher
I guess it should also include a condition... if the string has a "-" then do this.
.split is probably what you want. Here is a very simple example
JSFiddle Link
var string = 'Peggy Sue - Teacher'
var new1 = string.split('-')[0].trim();
var new2 = string.split('-')[1].trim();
console.log(new1); // "Peggy Sue"
console.log(new2); // "Teacher"
And if you want to place a simple condition on it looking for - you can do so with the following
var string = 'Peggy Sue - Teacher'
var new1 = string.indexOf('-') !== -1 ? string.split('-')[0].trim() : string
var new2 = string.indexOf('-') !== -1 ? string.split('-')[1].trim() : string
Second Fiddle
var result = str.split("-");
will give you an array with 2 members,
result[0] = Peggy Sue
result[1] = Teacher

Categories

Resources