I need some help. I need to match some value with one variable containing value which is comma separated string using Angular.js or Javascript. I am explaining my code below.
var special="2,1,4,5";
Here I need to search lets say 1 is present in this comma separated string or not. If the given value is present it will return true otherwise false.Please help.
With array split
var found = special.split(",").indexOf("1") > -1;
var special="2,1,4,5";
var found = special.split(",").indexOf("1") > -1;
console.log(found); // true
Just to prove that String's indexOf won't work
var special="2,11,4,5";
var found = special.indexOf("1") > -1;
console.log(found); // true but actual should be false as there is no 1
Try this,
var special="2,1,4,5";
var searchFor="1";
var index=special.split(",").indexOf(searchFor);
if(index === -1) return false;
else return true;
You can first convert the string to an array like this:
var specialArray = special.split(',');
Once you have an array you can use indexOf to find the item in the array.
var itemIndex = specialArray.indexOf('1');
itemIndex will be -1 when the value you're looking for isn't in the array. When the result of indexOf is greater than -1 it is the index of the item in the array.
You can use regular expression for this:
/(^|,)1(,|$)/.test("2,1,4,5") // => true
just to test negative case
/(^|,)1(,|$)/.test("2,11,4,5") // => false
If you have multiline string (that contains \r\n), use /(^|,)1(,|$)/m instead
Related
This function cleans up a string (removes all non-alphanumeric characters including underscores) then splits each letter into an array so that it can be reversed, then checked against the original.
At console.log(cleanStr) , it is returning the reversed array but I do not know why.
function checkIfPalindrome(str) {
var cleanStr = str.toLowerCase().replace(replace, "" ).split("");
var reversedStr = cleanStr.reverse();
console.log(cleanStr); // why is this returning reverseStr, the reversed array?
if (cleanStr == reversedStr){
return true
}
return false
}
checkIfPalindrome("five|\_/|four");
The reverse() method reverses an array in place - it mutates the array it's called on. Try creating a new array instead:
const cleanStr = str.toLowerCase().replace(replace, "" ).split("");
const reversedStr = [...cleanStr].reverse();
At console.log(cleanStr) , it is returning the reversed array but I do not know why.
Because reverse reverses it in place.
Separately, you have a problem here:
if (cleanStr == reversedStr){
If they were different arrays, that would always be false, even if they had the same contents.
If you want to make a copy of the array and then reverse it, throw a .slice() in there:
var reversedStr = cleanStr.slice().reverse();
// -----------------------^
...and then compare after turning them back into strings:
if (cleanStr.join("") === reversedStr.join(""))
(I'd probably change those variable names, too, as they don't refer to strings.)
And finally, any time you find yourself writing:
if (x == b) {
return true;
}
return false;
back up and write
return x == b;
instead. :-)
Is that possible to check if the variable array contains exactly the numbers 1,0,0,1?
For example,
var array = [1,0,0,1];
if (array === 1001) alert("success");
You can just join the array to check
The join() method joins all elements of an array (or an array-like
object) into a string and returns this string.
Note: You need to use == instead of === because join will return a string.
Like:
var array = [1, 0, 0, 1];
if ( array.join("") == 1001 ) alert("success");
As per suggestion below, you can also use === and compare it with a string.
var array = [1, 0, 0, 1];
if ( array.join("") === "1001" ) alert("success");
Please check more info about join: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join
Use the join() method to joins all elements of the array into a string and returns this string.
var elements = [1,0,0,1];
console.log(elements.join('') === "1001");
// expected output: true
Using the method join("") you conver your array into a string with out the commas
Then you use the includes("1001") to check for the expected result
Hope this is what you were looking for. Happy to explain or help in a better solution if needed.
var array = [1,0,0,1];
var string = array.join("");
console.log(string);
if (string.includes('1001')) alert("success");
Well, everyone gave a strict answer to your question; but I figured I would add on to it a little. Assuming you want this to be a little more dynamic. This way we check subsets of the array for the string you are looking for, rather than just the entire array.
Array.prototype.containsSequence = function(str, delimiter){
//Determines what is seperating your nums
delimiter = delimiter || '';
//Check the sub array by splicing it, then joining it
var checkSection = function (arr, start, end, str){
return arr.slice(start, end).join(delimiter) === str;
};
let start = 0; //start of our sub array
let end = str.length; //the length of the sub array
//Loop through each x size of sub arrays
while(end < this.length){
//Check the section, if it is true it contains the string
if(checkSection(this, start, end, str)){
return true;
}
//Incriment both start and end by 1
start++;
end++;
}
//We dont contain the values
return false;
};
///Test stuff
const ARRAY = [1,2,3,4,5,6,7,8,9,10];
if(ARRAY.containsSequence('456')){
console.log('It contains the str');
}else console.log('It does not contain');
I have two strings:
var a = 'ABCD';
var b = 'DEFG';
I need to compare these variables to check if there is not a common CHARACTER in the two strings.
So for this case return false (or do something...) because D is a common character in them.
You could merge the two strings then sort it then loop through it and if you find a match you could then exit out the loop.
I found this suggestion on a different stack overflow conversation:
var str="paraven4sr";
var hasDuplicates = (/([a-zA-Z]).*?\1/).test(str)
So if you merge the strings together, you can do the above to use a regexp, instead of looping.
Thank you every one. I tried your solutions, and finally got this :
Merging my two strings into one
to Lower Case,
Sort,
and Join,
using Regex Match if the Final Concatenated string contains any
repetitions,
Return 0 if no Repeat occur or count of repeats.
var a; var b;
var concatStr=a+b;
checkReptCharc=checkRepeatChrcInString(concatStr);
function checkRepeatChrcInString(str){
console.log('Concatenated String rec:' + str);
try{ return
str.toLowerCase().split("").sort().join("").match(/(.)\1+/g).length; }
catch(e){ return 0; }
}
I was also searching for solution to this problem, but came up with this:
a.split('').filter(a_ => b.includes(a_)).length === 0
Split a into array of chars, then use filter to check whether each char in a occurs in b. This will return new array with all the matching letters. If length is zero, no matching chars.
add toUpperCase() to a & b if necessary
So if it only duplicate strings in separate string arrays using .split(''), then I would sort the two string separately, and then do a binary search, start with the array of the shortest length, if the same length the just use the first one, and go character by character and search to see if it is in the other string.
This is obviously too late to matter to the original poster, but anyone else who finds this answer might find this useful.
var a = 'ABCD';
var b = 'DEFG';
function doesNotHaveCommonLetter(string1, string2) {
// split string2 into an array
let arr2 = string2.split("");
// Split string1 into an array and loop through it for each letter.
// .every loops through an array and if any of the callbacks return a falsy value,
// the whole statement will end early and return false too.
return string1.split("").every((letter) => {
// If the second array contains the current letter, return false
if (arr2.includes(letter)) return false;
else {
// If we don't return true, the function will return undefined, which is falsy
return true;
}
})
}
doesNotHaveCommonLetter(a,b) // Returns false
doesNotHaveCommonLetter("abc", "xyz") // Returns true
const _str1 = 'ABCD';
const _str2 = 'DEFG';
function sameLetters(str1, str2) {
if(str1.length !== str2.length) return false;
const obj1 = {}
const obj2 = {}
for(const letter of str1) {
obj1[letter] = (obj1[letter] || 1) + 1
}
for(const letter of str2) {
obj2[letter] = (obj2[letter] || 1) + 1
}
for(const key in obj1) {
if(!obj2.hasOwnProperty(key)) return false
if(obj1[key] !== obj2[key]) return false
}
return true
}
sameLetters(_str1, _str2)
I have an array of character with commas separating them. I need to split an array but retain my comma inbetween each character.
See below for an example array:
var myArray = [a,,,b,c,d,,,]
There's a comma in there between the characters "a" and "b". I need to retain the comma when converting the array to a string.
The output string needs to resemble this:
a,bcd,
This is what i'm currently doing to retain the commas:
myArray.toString().replace(/,/g, "");
The Array's toString() method basically does a join(",") which is why you are getting the extra commas in your string.
Instead use join("") if you want to join the elements without the delimiter being added as part of the string
var myArray = ["a",",","b","c","d",",",]
document.body.innerText = myArray.join("");
How about you use :
var myArray = [a,,,b,c,d,,,];
var str = myArray.join();
This will give a string of array elements, preserving the commas.
if you want it to maintain the centre comma you should create your array as
var myArray = [a,",",b,c,d,",",];
this will then treat the middle comma in the set of 3 as a string containing that character rather than the array seperator
You could change your regex, to replace item,item for item item.
myArray.toString().replace(/([a-z,]),([a-z,])/g, "$1$2")
Basically you have a sparse array and want to extract only filled values and convert it to string ? Here is one, probably not the best, solution :
var myArray = ['a',',',',','b',',','c']
var resultArray = [];
for(var i = 0; i < myArray.length; i++){
if(myArray[i] !== ','){// allow 0, false, null values, but not undefined
resultArray.push(myArray[i]);
}
}
console.log(resultArray);
Working plnkr : http://plnkr.co/edit/55T6PGI9DuTlvy6k88hr?p=preview, check the console of your broswer.
If this is an actual array of strings and you wanted only those with actual values, you could use the filter() function to filter out any non-undefined ones :
// Your example array
var input = ['a',,,'b','c','d',,,];
// Remove any undefined elements
var output = input.filter(function(e){ return e; }); // yields ['a','b','c','d']
You could then use the join() function to create a string with your elements :
var result = output.join(); // yields "a,b,c,d"
Example Snippet
var input = ['a',,,'b','c','d',,,];
document.write('INPUT: ' + input + '<br />');
var output = input.filter(function(e){ return e; });
document.write('OUTPUT: ' + output);
Not sure how to explain this in words, but is there any function in javascript that, when given a string , will return the number of times it occurs in an array?
For example:
var arr = ["a","b","c","d","c","c","b"];
var repeats = arr.count("c");
With repeats then being equal to 3 as "c" occurs 3 times.
I tried to look this up but I wasn't sure on how to word it so I didn't get anything useful.
You can create your own function or add it to the prototype of Array:
Array.prototype.count = function (val){
var result = 0;
for(var i = 0; i < this.length; i++){
if(this[i] === val) result++;
}
return result;
}
Then you can do ['a','b', 'a'].count('a') // returns 2
You can use array.filter()
var arr = ["a","b","c","d","c","c","b"];
var repeats = arr.filter(function(value) { return value==="c"; } ).length;
console.log(repeats)
arr.filter(function(v){return v=='c';}).length
Exact Word Match Example
var search_word = 'me';
var arr = ['help','me','please'];
arr.filter(function(el){return el === search_word}).length;
The filter function will return the element if the result of the function is true. The function is called on each element of the array. In this case, we are comparing the array element to our search word. If they are equal (true) the element is returned. We end up with an array of all the matches. Using .length simply gives us the number of items in the resulting array; effectively, a count.
Partial Match Example
If you were to want something a little more robust, for instance count the number of words that contain the letter l, then you could tokenize the string and scan the index, or use some regex which is a little more costly, but also more robust:
var search_word = 'l';
var arr = ['help','me','please'];
arr.filter( function(el){ return ( el.match(search_word) || [] ).length }).length;
Note that match also returns an array of matching elements, but an unsuccessful match returns undefined and not an empty array, which would be preferred. We need an array to use .length (the inside one), otherwise it would result in an error, so we add in the || [] to satisfy the case when no matches are found.