Javascript search not working as expected. How to resolve? - javascript

I am trying to execute search but it not working as per my expectation. It returning 0 instead 2. How to resolve it?
var number = '4,4';
alert(number.search(/4/g));

.search returns the index of the match. 4 is matched at index 0 of the string, so it returns 0. If you wanted to check how many times 4 occurs in the string, use .match instead, and check the .length of the match object:
var number = '4,4';
const match = number.match(/4/g);
console.log((match || []).length);
(the || [] is needed in case match is null, in which case you'd want 0, rather than a thrown error)

I think you mean to count the number of occurrences.
Use regex to store the occurrences and return the length to indicate the count.
var temp = "4,4";
var count = (temp.match(/4/g) || []).length;
console.log(count);

The search() method searches a string for a specified value, and returns the position of the match. if you what to count the occurrences you must to make something like this:
var number = '4,4';
var qtd = (number.match(/4/g) || []).length;
alert(qtd);

Related

Get String Specific Characters

I am trying to write some code that takes a uuid string and returns only the characters between the 2nd and 3rd _ characters in an array. What I currently have below is returning every character in the string in to the array. I have been looking at this for some time and am obviously missing something glaringly obvious I suppose. Can someone maybe point out what is wrong here?
var uuid = "159as_ss_5be0lk875iou_.1345.332.11.2"
var count = 0
var values = []
for(y=0; y<uuid.length; y++){
if(uuid.charAt(y) == '_'){
count++
}
if(count = 2){
values.push(uuid.charAt(y))
}
}
return values
EDIT:
So for my case I would want the values array to contain all of the characters in 5be0lk875iou
You can get the same behavior in less lines of code, like this:
let uuid = "159as_ss_5be0lk875iou_.1345.332.11.2"
let values = uuid.split("_")[2];
You can use the split function to do that:
let values = uuid.split("_");
By using the split function, you can get separate the whole string into smaller parts:
const parts = uuid.split("_");
This will return the following array:
["159as", "ss", "5be0lk875iou", ".1345.332.11.2"]
From here, you can take the string at index 2, and split it again to receive an array of characters:
const values = parts[2].split("");

Getting second digit in a string using Javascript + Regex?

I'm wondering how I can get the second digit of a string where we don't know the number of digits the second number will be and without using splice or substring.
Ex. Channel.0.This.13
Should Return: 13
I've seen a few similar questions but they
typically know the number of digits the second number will be or
use splicing and substring, which I do not want to use in this case.
I appreciate the help :)
You could use String.prototype.match
In case that the string does not have any number, which matches will return null, you should use optional chaining ?. for a safer array index access
const str = "Channel.0.This.13";
const res = str.match(/\d+/g)?.[1];
console.log(res);
Use this regex (\d*)$. This will return only group with numbers which in the end of the string.
try this:
^[^\d]*\d+[^\d]+(\d+).*
Example:
const secondDigit = "Channel.0.This.13".match(/^[^\d]*\d+[^\d]+(\d+).*/).pop();
console.log(Number(secondDigit)); // 13
Assuming the original string contains only alphabets, numbers and '.' (in between),
Here is my solution (Pseudo code):
String givenString;
regex=/([0-9]+)(\.[a-zA-Z]+)?(\.[0-9]+)/;
//below code will return an array or null (if no second number is present)
match=givenString.match(regex);
//access last element of array. It will be like '.13' , just remove '.' and you are good to go
match.pop()
Javascript Regex Docs:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Groups_and_Ranges
String.prototype.match() returns an array whose contents depend on the presence or absence of the global (g) flag, or null
const input1 = "Channel.0.This.13",
input2 = "Channel.0.This",
input3 = "Channel.This.";
const digitMatch = function (input) {
const digits = input.match(/\d+/g);
return (digits && digits[1]) || "Not Found";
};
console.log(digitMatch(input1));
console.log(digitMatch(input2));
console.log(digitMatch(input3));
if no matches are found.
It will help .*?\d+.*?(\d+).*$
"Channel.0.This.13.Channel.0.This.56".match(/.*?\d+.*?(\d+).*$/).pop()
// Output: 13
"Channel.0.This.13".match(/.*?\d+.*?(\d+).*$/).pop()
// Output: 13
You can reference the regex .match() key. str.match(reg)[1]
const str1 = 'Channel.0.This.13'
const str2 = 'some.otherStrin8..'
const str3 = '65 people.For.&*=20.them,98'
const regex = /\d+/g
function matchSecond(str, reg) {
str.match(reg)[1] ? output = str.match(reg)[1] : output = false
return output;
}
console.log(matchSecond(str1,regex))
console.log(matchSecond(str2,regex))
console.log(matchSecond(str3,regex))

JS Regex returning -1 & 0

I was tasked with the following:
take a string
print each of the vowels on a new line (in order) then...
print each of the consonants on a new line (in order)
The problem I found was with the regex. I originally used...
/[aeiouAEIOU\s]/g
But this would return 0 with a vowel and -1 with a consonant (so everything happened in reverse).
I really struggled to understand why and couldn't for the life of me find the answer. In the end it was simple enough to just invert the string but I want to know why this is happening the way it is. Can anyone help?
let i;
let vowels = /[^aeiouAEIOU\s]/g;
let array = [];
function vowelsAndConsonants(s) {
for(i=0;i<s.length;i++){
//if char is vowel then push to array
if(s[i].search(vowels)){
array.push(s[i]);
}
}
for(i=0;i<s.length;i++){
//if char is cons then push to array
if(!s[i].search(vowels)){
array.push(s[i]);
}
}
for(i=0;i<s.length;i++){
console.log(array[i]);
}
}
vowelsAndConsonants("javascript");
if(vowels.test(s[i])){ which will return true or false if it matches, or
if(s[i].search(vowels) !== -1){ and if(s[i].search(vowels) === -1){
is what you want if you want to fix your code.
-1 is not falsey so your if statement will not function correctly. -1 is what search returns if it doesn't find a match. It has to do this because search() returns the index position of the match, and the index could be anywhere from 0 to Infinity, so only negative numbers are available to indicate non-existent index:
MDN search() reference
Below is a RegEx that matches vowel OR any letter OR other, effectively separating out vowel, consonant, everything else into 3 capture groups. This makes it so you don't need to test character by character and separate them out manually.
Then iterates and pushes them into their respective arrays with a for-of loop.
const consonants = [], vowels = [], other = [];
const str = ";bat cat set rat. let ut cut mut,";
for(const [,cons,vow,etc] of str.matchAll(/([aeiouAEIOU])|([a-zA-Z])|(.)/g))
cons&&consonants.push(cons) || vow&&vowels.push(vow) || typeof etc === 'string'&&other.push(etc)
console.log(
consonants.join('') + '\n' + vowels.join('') + '\n' + other.join('')
)
There are a couple of inbuilt functions available:
let some_string = 'Mary had a little lamb';
let vowels = [...some_string.match(/[aeiouAEIOU\s]/g)];
let consonents = [...some_string.match(/[^aeiouAEIOU\s]/g)];
console.log(vowels);
console.log(consonents);
I think that you don't understand correctly how your regular expression works. In the brackets you have only defined a set of characters you want to match /[^aeiouAEIOU\s]/g and further by using the caret [^]as first in your group, you say that you want it to match everything but the characters in the carets. Sadly you don't provide an example of input and expected output, so I am only guessing, but I thing you could do the following:
let s = "avndexleops";
let keep_vowels = s.replace(/[^aeiouAEIOU\s]/g, '');
console.log(keep_vowels);
let keep_consonants = s.replace(/[aeiouAEIOU\s]/g, '');
console.log(keep_consonants);
Please provide example of expected input and output.
You used:
/[^aeiouAEIOU\s]/g
Instead of:
/[aeiouAEIOU\s]/g
^ means "not", so your REGEX /[^aeiouAEIOU\s]/g counts all the consonants.

How can I sum all numbers 1 from a string?

I need to sum all numbers 1 from a string!
For example: "00110010" = 1+1+1 = 3...
psum will receive this result and then I will check
if(psum >= 3){
return person;
}
I need to find a way to solve it in javascript ES6 but I can't use any for, while or forEach loop, unfortunately!!!
Could you help me?
You need to use the reduce() method.
let input = '00110010'
let array = input.split("").map(x => parseInt(x));
let sum = array.reduce((acc, val) => {
return acc + val;
});
console.log(sum)
In one statement:
let psum = "00110010".split('').reduce((t, n) => {return t + parseInt(n)}, 0);
console.log(psum);
Note that summing the numbers 1 comes down to counting the numbers 1, which is what the following solutions do in different ways:
With match
You could use a regular expression /1/g:
var p = "00110010";
var psum = (p.match(/1/g) || []).length;
console.log(psum);
match returns an array of substrings that match with the pattern 1. The / just delimit this regular expression, and the g means that all matches should be retrieved (global). The length of the returned array thus corresponds to the number of 1s in the input. If there are no matches at all, then match will return null, so that does not have a .length property. To take care of that || [] will check for that null (which is falsy in a boolean expression) and so [] will be taken instead of null.
With replace
This is a similar principle, but by matching non-1 characters and removing them:
var p = "00110010";
var psum = p.replace(/[^1]/g, "").length;
console.log(psum);
[^1] means: a character that is not 1. replace will replace all matches with the second argument (empty string), which comes down to returning all characters that do not match. This is like a double negative: return characters that do not match with not 1. So you get only the 1s :-) .length will count those.
With split:
var p = "00110010";
var psum = p.split("1").length - 1;
console.log(psum);
split splits the string into an array of substrings that do not have the given substring ("1"). So even if there are no "1" at all, you get one such substring (the whole string). This means that by getting the length, we should reduce it by 1 to get the number of 1s.
With a recursive function:
var p = "00110010";
var count1 = p => p.length && ((p[0] == "1") + count1(p.slice(1)));
var psum = count1(p);
console.log(psum);
Here the function count1 is introduced. It first checks if the given string p is empty. If so, length is zero, and that is returned. If not empty, the first character is compared with 1. This can be false or true. This result is converted to 0 or 1 respectively and added to a recursive call result. That recursive call counts the number 1s in the rest of the input (excluding the first character in which the 1s were already counted).

How to check if one element of an array matches another element in same array?

Very new to javascript so bear with me...
I need to check one element of an array(arr[1]), which contains a string, against another element of the same array(arr[0]) to determine if any letters included in element arr[1] are included in arr[0]. Those letters can be in any order, upper or lower case, and don't have to occur the same number of times (i.e. arr[0]="hheyyy" and arr[1]="hey" is fine). This is what i have (which works) but I was curious if anyone has a better/more simple way of doing this? -thanks in advance.
function mutation(arr) {
//splits the array into two separate arrays of individual letters
var newArr0 = arr.join('').toLowerCase().split('').slice(0,arr[0].length);
var newArr1 = arr.join('').toLowerCase().split('').slice(arr[0].length);
var boolArr = [];
//checks each letter of arr1 to see if it is included in any letter of arr0
for(var i = 0; i < newArr1.length; i++)
boolArr.push(newArr0.includes(newArr1[i]));
//results are pushed into an array of boolean values
if (boolArr.indexOf(false) !==-1)
return false; //if any of those values are false return false
else return true;
}
mutation(["hello", "hey"]); //returns false
You could use a regular expression:
function mutationReg(arr) {
return !arr[1].replace(new RegExp('['+arr[0].replace(/(.)/g,'\\\\$1')+']', "gi"), '').length;
}
This escapes every character in the second string with backslash (so it cannot conflict with regular expression syntax), surrounds it with square brackets, and uses that as a search pattern on the first string. Any matches (case-insensitive) are removed from the result, so that only characters are left over that don't occur in the second string. The length of the result is thus an indication on whether there was success or not. Applying the ! to it gives the correct boolean result.
This might not be the fastest solution.
Here is another ES6 alternative using a Set for good performance:
function mutation(arr) {
var chars = new Set([...arr[0].toLowerCase()]);
return [...arr[1].toLowerCase()].every (c => chars.has(c));
}
You can use Array.from() to convert string to an array, Array.prototype.every(), String.prototype.indexOf() to check if every charactcer in string converted to array is contained in string of other array element.
var arr = ["abc", "cab"];
var bool = Array.from(arr[0]).every(el => arr[1].indexOf(el) > -1);
console.log(bool);

Categories

Resources