I am having an array with string:
var dict =["johndoe","johnrte","jahnaoi"];
I want to make a function (with regex or other) to check if "str" with missing letter fit one of its item. Missing letter is represented by "#".
Let's say that the string with missing letter is "j#hn#oe".
I started that way, but I think I am not going to right way.
function Checkword(str) {
// Check were is the #
var indices = [0]
for (var i = 0; i < str.length; i++) {
if (str[i] === "#") indices.push(i);
}
var regexel = "/^";
for (var index = 0; index < indices.length; index++) {
regexel.concat(str.substring(indices[index - 1], indices[index]));
regexel.concat("[a-z]");
}
regexel.concat("$/");
var reg = new Regex(regexel);
for (r = 0; r < dict.length; i++) {
if (reg.test(dict[r]) {
console.log(dict[r]);
}
}
}
Checkword("j#hn#oe");
In this case, it would return first and last item.
*** Edit after comment:
Which word should pass my test:
If str is j#hndo#=> dict[0], dict[2].
If str is j####### => dict[0], dict[1], dict[2];
IF str is Jonh#oe=> dict[0]
if str is a#ze#ts=> nothing.
Thanks to the comment, this is the answer which is a lot more easier than expected. Thank you!
var dict =["johndoe","johnrte","jahnaoi"];
var dict =["johndoe","johnrte","jahnaoi"];
function ismissing(str){
while(str.indexOf("#")>0){
str=str.replace('#', '[a-z]{1}');
}
var reg=new RegExp(str);
console.log(reg);
for(i=0;i<dict.length;i++){
if(reg.test(dict[i]))
{console.log(dict[i])};
}
}
ismissing("j#hn#o#");
output=>
/j[a-z]{1}hn[a-z]{1}o[a-z]{1}/
johndoe
jahnaoi
undefined
Related
I'm doing an algorithm on Codesignal.
For s = "abacabad", the output should be
firstNotRepeatingCharacter(a) = 'c'.
There are 2 non-repeating characters in the string: 'c' and 'd'. Return c since it appears in the string first.
For s = "abacabaabacaba", the output should be
firstNotRepeatingCharacter(s) = '_'.
There are no characters in this string that do not repeat.
Code below:
function firstNotRepeatingCharacter(a) {
let b = {};
let len = a.length;
for (let i = 0; i < len; i++) {
let tmp = a.charAt(i);
if (b[tmp]) {
b[tmp] += 1; //explain here
}
else {
b[tmp] = 1;
}
}
for (var prop in b) {
if (b[prop] == 1) { //explain here
return prop;
}
}
return '_';
}
Actually in the above b is an object whose keys are different letters of the string and the values of those keys are count of respective lettter in the string.
key => letter
value => Count of that letter
tmp will be character through you are iterating.
if (b[tmp]) checks whether the letter is already added to the object.
If its already there so increase the count.
Otherwise set it to one.
In the second loop if (b[prop] == 1) checks whether the count of certain letter is 1. means that it only occurred once in the string so return the letter.
I'm working on a Racker Rank problem whose function in JavaScript receives a single parameter (input).
Input Format:
The first line contains an integer, (the number of test cases).
Each line of the subsequent lines contain a String.
I need to print the even-indexed and odd-indexed characters of each string (S) separated by a space on a single line (see the Sample below for more detail).
2
Hacker
Rank
Hce akr
Rn ak
Is there a way to read the input line-by-line and save each string in a specific variable? If I achieve that I know how to solve the problem by iterating through the string. Otherwise, I'm lost. If not, how else could I handle the input? Thanks!
Readline doesn't seem to be the way to go.
function processData(input) {
//Enter your code here
}
process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
_input += input;
});
process.stdin.on("end", function () {
processData(_input);
});
What I have tried without success:
function processData(input) {
let myArray = input.split("\n");
let even_indexed = "";
let odd_indexed = "";
for (let i = 1; i <= myArray.length; i++) {
let str = myArray[i];
let len = str.length;
for (let j = 0; j < len; j++){
if (j % 2 == 0) { //check if the index is even;
even_indexed.concat(str[j]);
}
else {
odd_indexed.concat(str[j]);
}
}
}
console.log("%s %s", even_indexed, odd_indexed);
}
Can't you just use split() method with a newline operator?
<script>
let x= `Hey
I'm
a
multiline
string`
console.log(x.split("\n"))
</script>
The result will be an array on which every element represents a line of your input.
I made this pretty quickly so I apologize for it being kinda messy and I know there are probably more efficient ways of doing this, but it does what you are asking for.
let input = `This
is
a
multiline
string`
let splitWords = [];
input.split(/\r?\n/).forEach(function(e){ // Split the array by \n (newline) and/or \r (carriage return)
currentLine = {evenIndex: [], oddIndex: []}
for(let i = 0; i < e.length; i++){
if((i + 1)%2 === 0){
currentLine.evenIndex.push(e[i]);
}
else{
currentLine.oddIndex.push(e[i]);
}
}
splitWords.push(currentLine);
});
splitWords.forEach(function(e){
console.log(e.oddIndex.join('') + " " + e.evenIndex.join(''))
});
I try to match/get all repetitions in a string. This is what I've done so far:
var str = 'abcabc123123';
var REPEATED_CHARS_REGEX = /(.).*\1/gi;
console.log( str.match(REPEATED_CHARS_REGEX) ); // => ['abca', '1231']
As you can see the matching result is ['abca', '1231'], but I excpect to get ['abc', '123']. Any ideas to accomplish that?
2nd question:
Another thing I excpect, is to make it possible to change the duration how often a char needs to be in the string to get matched...
For example if the string is abcabcabc and the repetation-time is set to 2 it should result in ['abcabc']. If set to 3 it should be ['abc'].
Update
A non-RegExp solution is perfectly alright!
Well, I think falsetru had a good idea with a zero-width look-ahead.
'abcabc123123'.match(/(.+)(?=\1)/g)
// ["abc", "123"]
This allows it to match just the initial substring while ensuring at least 1 repetition follows.
For M42's follow-up example, it could be modified with a .*? to allow for gaps between repetitions.
'abc123ab12'.match(/(.+)(?=.*?\1)/g)
// ["ab", "12"]
Then, to find where the repetition starts with multiple uses together, a quantifier ({n}) can be added for the capture group:
'abcabc1234abc'.match(/(.+){2}(?=.*?\1)/g)
// ["abcabc"]
Or, to match just the initial with a number of repetitions following, add the quantifier within the look-ahead.
'abc123ab12ab'.match(/(.+)(?=(.*?\1){2})/g)
// ["ab"]
It can also match a minimum number of repetitions with a range quantifier without a max -- {2,}
'abcd1234ab12cd34bcd234'.match(/(.+)(?=(.*?\1){2,})/g)
// ["b", "cd", "2", "34"]
This solution may be used if you don't want to use regex:
function test() {
var stringToTest = 'find the first duplicate character in the string';
var a = stringToTest.split('');
for (var i=0; i<a.length; i++) {
var letterToCompare = a[i];
for (var j=i+1; j<a.length; j++) {
if (letterToCompare == a[j]) {
console.log('first Duplicate found');
console.log(letterToCompare);
return false;
}
}
}
}
test()
The answer above returns more duplicates than there actually are. The second for loop causes the problem and is unnecessary. Try this:
function stringParse(string){
var arr = string.split("");
for(var i = 0; i<arr.length; i++){
var letterToCompare = arr[i];
var j= i+1;
if(letterToCompare === arr[j]){
console.log('duplicate found');
console.log(letterToCompare);
}
}
}
var duplicateCheck = function(stru) {
var flag = false;
for (let o = 0; o < stru.length; o++) {
for (let p = 0; p < stru.length; p++) {
if (stru.charAt(o) === stru.charAt(p) && o!==p) {
flag = true;
break;
}
}
}
return flag;
}
true ==> duplicate found
I'm working on alternating the case of a string (for example asdfghjkl to AsDfGhJkL).
I tried to do this. I found some code that is supposed to do it, but it doesn't seem to be working.
var str="";
var txt=document.getElementById('input').value;
for (var i=0; i<txt.length; i+2){
str = str.concat(String.fromCharCode(txt.charCodeAt(i).toUpperCase()));
}
Here's a quick function to do it. It makes the entire string lowercase and then iterates through the string with a step of 2 to make every other character uppercase.
var alternateCase = function (s) {
var chars = s.toLowerCase().split("");
for (var i = 0; i < chars.length; i += 2) {
chars[i] = chars[i].toUpperCase();
}
return chars.join("");
};
var txt = "hello world";
console.log(alternateCase(txt));
HeLlO WoRlD
The reason it converts the string to an array is to make the individual characters easier to manipulate (i.e. no need for String.prototype.concat()).
Here an ES6 approach:
function swapCase(text) {
return text.split('').map((c,i) =>
i % 2 == 0 ? c.toLowerCase() : c.toUpperCase()
).join('');
}
console.log(swapCase("test"))
You should iterate the string and alternate between upper-casing the character and lower-casing it:
for (var i=0; i<txt.length; i++) {
var ch = String.fromCharCode(txt.charCodeAt(i);
if (i % 2 == 1) {
ch = ch.toUpperCase();
} else {
ch = ch.toLowerCase();
}
str = str.concat(ch);
}
I have a gigantic list (800 items) and one really long string. I want to get the first item in the array that matches the part of the string and stored in a variable.
My code currently:
for (var i = 0; i<gigantic_genre_array.length; i++) {
var test_genre = thelongstr.indexOf(gigantic_genre_array[i]);
if(test_genre != -1) {
tag1 = gigantic_genre_array[test_genre];
alert(tag1);
}
}
This doesn't work like I thought it would, any suggestions?
Try this:
for(var i = 0; i<gigantic_genre_array.length; i++){
var test_genre = thelongstr.indexOf(gigantic_genre_array[i]);
if(test_genre!=-1){
tag1 = gigantic_genre_array[i];
alert(tag1);
}
}
Do the process reversely it will be efficient too.
var wordArray = thelongstr.split(' ');
for(var i=0,len = wordArray.length; i < len; i++)
{
if(gigantic_genre_array.indexOf(wordArray[i]) > -1)
{
alert(wordArray[i]);
}
}
You may create a RegExp based on the array and test it against the string:
var gigantic_genre_array=['foo','bar','foobar'];
var thelongstr='where is the next bar';
alert(new RegExp(gigantic_genre_array.join('|')).exec(thelongstr)||[null][0]);
//returns bar