This question already has answers here:
How to do case insensitive string comparison?
(23 answers)
How to check if a string contains text from an array of substrings in JavaScript?
(24 answers)
Closed 5 years ago.
I am checking a string input whether it contains any of an array of strings or not. It is passing most of the tests but not the below one.
Can anyone break my code down why it is not working properly?
function checkInput(input, words) {
var arr = input.toLowerCase().split(" ");
var i, j;
var matches = 0;
for(i = 0; i < arr.length; i++) {
for(j = 0; j < words.length; j++) {
if(arr[i] == words[j]) {
matches++;
}
}
}
if(matches > 0) {
return true;
} else {
return false;
}
};
checkInput("Visiting new places is fun.", ["aces"]); // returns false // code is passing from this test
checkInput('"Definitely," he said in a matter-of-fact tone.',
["matter", "definitely"])); // returns false; should be returning true;
Thank you for your time!
You can use functional methods for this. Try Array.some.
const words = ['matters', 'definitely'];
const input = '"Definitely," he said in a matter-of-fact tone.';
console.log(words.some(word => input.includes(word)));
You can use array#includes to check if a word exist in your input and convert both your input and words in lower case and then use array#includes.
function checkInput(input, words) {
return words.some(word => input.toLowerCase().includes(word.toLowerCase()));
}
console.log(checkInput('"Definitely," he said in a matter-of-fact tone.',
["matter", "definitely"]));
You can create regular expression and use i flag to specify case-insensitivity
function checkInput(input, words) {
return words.some(word => new RegExp(word, "i").test(input));
}
console.log(checkInput('"Definitely," he said in a matter-of-fact tone.',
["matter", "definitely"]));
Related
This question already has answers here:
Javascript Pangram Regex
(9 answers)
Closed 5 months ago.
Summary of problem:
Essentially I want to perform the following function:
function isPangram(string){
if (all characters a - z are present in the string) {
return true;
} else {
return false;
}
}
Here's what I've tried thus far:
function isPangram(string){
if (string.contains(/[a-z]/)) {
return true;
} else {
return false;
}
}
function isPangram(string){
if (string.matchAll(/[a-z]/) {
return true;
} else {
return false;
}
}
function isPangram(string){
for (let i = 0; i < string.length; i++) {
if (string[i] = /[a-z]/) {
return true;
} else {
return false;
}
}
I've laid out the problem and I have the solution but I'm unaware of the proper syntax that allows me to get the solution I'm looking for. So! I'm asking for syntax recommendations that can help lead me in the right direction. I can struggle from there~
Try using this expression:
new Set("<your_string>".toLowerCase().replace(/[^a-z]/g, "") ).size === 26
A way to accomplish that could be iterating all characters in test string, and match each character against an "alphabet" array. If character is found, then it gets removed from the alphabet.
When all characters are scanned, if alphabet doesn't contain any elements, it means test string contained all characters in the alphabet.
const alphabet = []
//const testString = '123badcfehgjilknmporqtsvuxwzy000'
const testString = '123badcfehgtsvuxwzy000'
// POPULATE alphabet WITH ASCII CHARACTERS CODES FROM a TO z
for (let i = 97; i < 123; i++) {
alphabet.push(i)
}
// SCAN ALL CHARACTERS IN testString
for (let i = 0; i < testString.length; i++) {
let pos = alphabet.indexOf(testString[i].charCodeAt(0))
if (pos != -1) {
// IF CURRENT CHARACTER IS PRESENT IN OUR alphabet ARRAY, REMOVE IT
alphabet.splice(pos, 1)
}
}
if (alphabet.length == 0) {
console.log('All alphabet letters found in test string')
} else {
console.log('These alphabet letters were not found: ', alphabet.map(c => String.fromCharCode(c)) )
}
This question already has answers here:
return the first non repeating character in a string in javascript
(32 answers)
Closed 1 year ago.
I tried to solve the problem below on a site, but they keep saying that something is not right when I reach certain tests.
Given a string s consisting of small English letters, find and return the first instance of a non-repeating character in it. If there is no such character, return "_".
I tried this
function firstNotRepeatingCharacter(s) {
let strArr = s.replace(" ", "").split(""),
newArr = [];
for (let i = 0; i < strArr.length; i++) {
newArr = strArr.filter(lol => lol === strArr[i]);
if (newArr.length === 1) {
return newArr[0];
};
};
return "_";
};
console.log(firstNotRepeatingCharacter("abacabad"));
It works for 16 out of 19 tests. why not all
Thanks all!
I've found an answer.
function firstNotRepeatingCharacter(s) {
let strArr = s.replace(" ", "").split("");
for (let str of strArr)
if(strArr.indexOf(str) == strArr.lastIndexOf(str))
return str;
return "_";
};
console.log(firstNotRepeatingCharacter("abacabad"));
another approach with a better time complexity:
function firstNotRepeatingCharacter(s) {
const seenBefore = new Set();
let result = "_";
for (let i = s.length; i--;) {
const char = s.charAt(i);
if (seenBefore.has(char)) continue;
seenBefore.add(char);
result = char;
}
return result;
}
console.log(firstNotRepeatingCharacter("abacabad"));
This question already has answers here:
Remove consecutive duplicate characters in a string javascript
(5 answers)
Closed 1 year ago.
I have seen a few examples of this, but they're either not in JS or are terribly inefficient (like the solution I have now). Basically what I want done is a function that takes in a string and removes any characters that are adjacent and the same. As an example, "jjjavvvaaassscript" would become "javascript". What I'm not looking for is where it would become "javscript" (eliminating the second "a"). I do have a working function shown below, but it's absolutely horrendous and I'm looking for a better way to do it.
function removeChar(text, index) {
return(text.slice(0,index)+text.slice(index+1));
}
function removeDuplicates(text) {
var prevChar = "";
var finalT = text;
var i = 0;
for(i = 0; i < text.length; i++) {
if(finalT.charAt(i) == prevChar) {
if(i > finalT.length) {
return finalT;
} else {
finalT = removeChar(finalT, i);
i--;
}
} else {
prevChar = finalT.charAt(i);
}
}
return finalT;
}
Any help would be greatly appreciated!
I'd use a regular expression to match a character, then backreference it as many times as possible (so, for example, it'll match jjj, or a, or vvv, etc), and then replace with the one character:
const removeDuplicates = str => str.replace(/(.)\1*/g, '$1');
console.log(removeDuplicates('jjjavvvaaassscript'));
If you had to iterate more manually, similar to your current method, then:
const removeDuplicates = str => {
let lastChar = str[0];
let finalT = str[0];
for (const char of str.slice(1)) {
if (lastChar !== char) finalT += char;
lastChar = char;
}
return finalT;
};
console.log(removeDuplicates('jjjavvvaaassscript'));
This question already has answers here:
Are JavaScript strings immutable? Do I need a "string builder" in JavaScript?
(10 answers)
Closed 3 years ago.
function kebabToSnake(string){
var replacedString = string;
for(i = 0; i < string.length; i++){
if(string[i] === "-"){
replacedString[i] = "_";
}
}
return replacedString;
}
I am new in js, can someone explain why this code doesn't work?
String are immutable, that means, you can not assign a character to a position of the string.
You could use an array instead and relace only the wanted character. Later you need to join the array to a string.
function kebabToSnake(string) {
var replacedString = Array.from(string);
for (i = 0; i < string.length; i++){
if (string[i] === "-"){
replacedString[i] = "_";
}
}
return replacedString.join('');
}
console.log(kebabToSnake('abc-def-ghi'));
A bit shorter approach by using the mapping parameter of Array.from.
function kebabToSnake(string) {
return replacedString = Array
.from(string, c => c === '-' ? '_' : c)
.join('');
}
console.log(kebabToSnake('abc-def-ghi'));
Finally a regular expression, which looks for a single minus sign /-/ and replaces all (g - for global - flag) with an underscore '_'.
function kebabToSnake(string) {
return string.replace(/-/g, '_');
}
console.log(kebabToSnake('abc-def-ghi'));
This question already has answers here:
Replace method doesn't work
(4 answers)
Closed 7 years ago.
I want to know why this procedure doesn't replace words
I have to do a procedure which reads a string and replace all word like this {{employee.Name}} into a value on the ticket's scope
var mySplitResult = Val.split(' ');
for (var i = 0; i < mySplitResult.length; i++) {
if (mySplitResult[i].match("{{") && mySplitResult[i].match(".")) {
var start = mySplitResult[i].lastIndexOf(".") + 1;
var end = mySplitResult[i].indexOf("}}");
var result = mySplitResult[i].substring(start, end);
for (var key in ticket.PNData) {
if (key == result) {
change.replace(mySplitResult[i], ticket.PNData[key]);
alert(change)
}
}
}
}
In JavaScript strings are immutable which means you must assign the result to a variable.
mySplitResult[i] = mychange.replace(mySplitResult[i], ticket.PNData[key]);