Using Regex as conditional in Javascript [duplicate] - javascript

This question already has answers here:
How to check if character is a letter in Javascript?
(17 answers)
Closed 3 years ago.
Hello I am having trouble trying to use Regex to check if each character in string is an alphabet.
First let me introduce the problem itself.
There is a string mixed with special chars and alphabets and suppose to return the number of alphabets only.
My code/pseudo code for problem is :
//Create var to hold count;
var count = 0;
//Loop thru str
for(let char of str){
//Check if char is a alphabet
***if(char === /[A-Za-z]/gi){***
//if so add to count
count ++;
}
//return count;
return count;
}
How can I use Regex in a conditional statement to check if each char is an alphabet????
Please help!

const pattern = /[a-z]/i
const result = [...'Abc1'].reduce((count,c) => pattern.test(c) ? count+1 : count, 0)
console.log(result) // 3

Related

How can I found the index of a array of characters in a string without looping on the array characters [duplicate]

This question already has answers here:
Pass an array of strings into JavaScript indexOf()? Example: str.indexOf(arrayOfStrings)?
(4 answers)
Is there a version of JavaScript's String.indexOf() that allows for regular expressions?
(22 answers)
Closed 1 year ago.
i'm searching a simple way to find the index of one character / string between a list of characters.
Something which looks like
"3.14".indexOf([".",","])
"3,14".indexOf([".",","])
Both should return 1.
One way:
const testRegex = /\.|,/
const match = testRegex.exec("3.14");
console.log(match && match.index)
It uses a regular expression to search for either character, and uses the exec method on regular expressions which returns an object that has the index of the start of the match.
You can loop through the array and return the first character's index whose index is not -1:
function getIndex(str, array){
for(e of array){
let index = str.indexOf(e);
if(index != -1){
return index;
}
}
}
console.log(getIndex("3.14", [".",","]))
console.log(getIndex("3,14", [".",","]))
You can also use Array.reduce:
function getIndex(str, array){
return array.reduce((a,b) => a == -1 ? a = str.indexOf(b) : a, -1)
}
console.log(getIndex("3.14", [".",","]))
console.log(getIndex("3,14", [".",","]))

JavaScript count digits in a string [duplicate]

This question already has answers here:
Count the number of integers in a string
(6 answers)
Closed 1 year ago.
I want to know how many digits 0 to 9 are in a string:
"a4 bbb0 n22nn"
The desired answer for this string is 4.
My best attempt follows. Here, I'm iterating through each char to check if it's a digit, but this seems kind of heavy-handed. Is there a more suitable solution?
const str = 'a4 bbb0 n22nn'
const digitCount = str.split('').reduce((acc, char) => {
if (/[0-9]/.test(char)) acc++
return acc
}, 0)
console.log('digitCount', digitCount)
With the regular expression, perform a global match and check the number of resulting matches:
const str = 'a4 bbb0 n22nn'
const digitCount = str.match(/\d/g)?.length || 0;
console.log('digitCount', digitCount)

RegEx for checking multiple matches [duplicate]

This question already has answers here:
How can I match overlapping strings with regex?
(6 answers)
Closed 3 years ago.
I want to match all occurrence in string.
Example:
pc+pc2/pc2+pc2*rr+pd
I want to check how many matched of pc2 value and regular expression is before and after special character exists.
var str = "pc+pc2/pc2+pc2*rr+pd";
var res = str.match(new RegExp("([\\W])pc2([\\W])",'g'));
But I got only +pc2/ and +pc2* and /pc2+ not get in this.
Problem is in first match / is removed. So after that, it is starting to check from pc2+pc2*rr+pd. That's why /pc2+ value does not get in the match.
How do I solve this problem?
You need some sort of recursive regex to achieve what you're trying to get, you can use exec to manipulate lastIndex in case of value in string is p
let regex1 = /\Wpc2\W/g;
let str1 = 'pc+pc2/pc2+pc2*rr+pd';
let array1;
let op = []
while ((array1 = regex1.exec(str1)) !== null) {
op.push(array1[0])
if(str1[regex1.lastIndex] === 'p'){
regex1.lastIndex--;
}
}
console.log(op)

Capitalizing certain strings in an array [duplicate]

This question already has answers here:
Convert string to Title Case with JavaScript
(68 answers)
How do I make the first letter of a string uppercase in JavaScript?
(96 answers)
How can I capitalize the first letter of each word in a string using JavaScript?
(46 answers)
Closed 4 years ago.
I basically want to capitalize the first letter in every word in a sentence, assuming that str is all lowercase. So here, I tried to split the string, letter by letter, then by using for loop, I would capitalize whatever the letter that's after a space. Here's my code and could you please point out where I coded wrong? Thank you.
function titleCase(str) {
var strArray = str.split('');
strArray[0].toUpperCase();
for (i=0; i<strArray.length;i++){
if (strArray[i]===" "){
strArray[i+1].toUpperCase();
}
}
return strArray.join('');
}
You need to assign the values:
function titleCase(str) {
var strArray = str.split('');
strArray[0] = strArray[0].toUpperCase();
for (i=0; i<strArray.length;i++){
if (strArray[i]===" "){
strArray[i+1] = strArray[i+1].toUpperCase();
}
}
return strArray.join('');
}
You can try following
function titleCase(str) {
var strArray = str.split(' ');
for (i=0; i<strArray.length;i++){
strArray[i] = strArray[i].charAt(0).toUpperCase() + strArray[i].slice(1);
}
return strArray.join(' ');
}
console.log(titleCase("i am a sentence"));

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)

Categories

Resources