javascript check values are same or not within double quotes? - javascript

In javascript if any variable has multiple values seperated by comma within double quotes,then how to check that values are same or not
var str= "0,1,-1";
How to check this variable.

The author wants to compare these 3 values. You most separate this variable with split:
var str= "0,1,-1",
arr = str.split(',');
all are same or not ie, true are false compare this array with function every
var str= "0,1,-1",
arr = str.split(',');
var res = arr.every(function (item) {
return item == arr[0];
})
console.log(res);

Short solution using String.prototype.split() and Set object:
var hasSameValues = function (s) {
return (new Set(s.split(','))).size === 1;
};
console.log(hasSameValues("0,1,-1"));
console.log(hasSameValues("1,1,1"));
console.log(hasSameValues("2,-2,2"));

you can split and then check for every item in splitted array.
check the fiddle
code is below -
var val = "1, 01, 0001";
var result = function(val)
{
var l = val.length;
if(l == 0)
{
return false;
}
else
{
//because all the values in 'val' fields are number
var f = Number.parseInt(val[0]) ;
for(i=1; i< l; i++)
{
if(Number.parseInt(val[i]) != f)
{
return false;
}
}
return true;
}
}(val.split(','))
alert(result);

Related

How to find whether an array has other element or not?

I have any array
var myArr = [1,1,1,1,1];
if all the elements in an array are same, then we return true and else false.
eg : myArr[1,1,1,1,1] return true;
myArr[1,2,1,1,1] return false;
for(var i=0; i<myArr.length; i++){
if(myArr[i] != myArr[i+1]){
flg = false;
}
}
Can anyone help me to design this code.
That's why .every is there
var myArr = [1,1,1,1,2 ];
var myArr2 = [1,1,1,1,1,2,3,4,5];
console.log(myArr.every(o=> myArr2.indexOf(o) >=0 ))
Create a function and return false if any element of a array is not equal to 1 .
function retStat( myArr ){
for(var i=0; i<myArr.length; i++){
if(myArr[i] != 1){
return false;
}
}
return true;
}
arr1 = [1,1,1,1,1];
arr2 = [1,2,1,1,1];
console.log( retStat( arr1 ) ); // true
console.log( retStat( arr2 ) ); // false
This can also be achieved without loop. You can check for the first element to the entire string represenattion of the array. If the match is found for all characters in the string it will give you blank value as ''. Using this you can know if the array has all same elements or there is different elements present there.
function isSame(arr){
var str = arr.join('');
var re = new RegExp(arr[0],"g");
var replacedStr = str.replace(re,'');
return !Boolean(replacedStr);
}
var myArr = [1,1,1,1,1];
console.log(isSame(myArr));
myArr = [1,2,1,1,1];
console.log(isSame(myArr));
myArr = [1,1,1,5,1];
console.log(isSame(myArr));
Since you want to check whether all elements in array are the same you can compare all of them to first element.
Function some returns as its callback returns true, so callback isn't called after first mismatch is found.
console.log(check([1,1,1]));
console.log(check([1,2,3]));
console.log(check([]));
function check(arr){
if (!arr.length){
return false;
}
return !arr.some(el=> el !== arr[0]);
}
I think this works:
<script type="text/javascript">
var myArr = [1,1,1,1,1];
flg=true;
for(var i=0; i<myArr.length; i++)
{
if(i==(myArr.length-1))
{
if(myArr[i]!=myArr[i-1])
{
flg=false;
}
}
else
{
if(myArr[i] != myArr[i+1])
{
flg=false;
return false;
}
}
}
console.log(flg);
</script>
Small mistake, you are checking for next element myArr[i+1] which is undefined at last loop
Check with condition myArr.length-1
for(var i=0; i<myArr.length-1; i++){
if(myArr[i] != myArr[i+1]){
flg = false;
break;
}
}
Here is a solution inspired by this answer https://stackoverflow.com/a/9229821/5061000
What does the below function in snippet do?
Removes all the duplicate items,
Returns true if .length == 1 (i.e. all values are the same!).
function array_all_same(a) {
return a.filter(function(item, pos) {
return a.indexOf(item) == pos;
}).length == 1;
}
var myArr1 = [1, 1, 1, 1, 1];
console.log(array_all_same(myArr1));
var myArr2 = [1, 2, 1, 1, 1];
console.log(array_all_same(myArr2));
Hope it helps!

Find the replaced part in a string using Javascript

function str_replace(str , part_to_replace , replace_with) {
var res = str.replace(part_to_replace , replace_with);
return res;
}
console.log(str_replace("amir" , "ir" , "er")) //returns "amer"
I want the function to return "e" which is the only part that changed aka replaced part so how i am supposed to do that ?
thanks in advance.
You could iterate all characters and take only the changed ones.
function check(a, b) {
if (a.length !== b.length) { return; }
return b
.split('') // take an array
.filter(function (c, i) { // filter
return a[i] !== c; // check characters
})
.join(''); // return string
}
function str_replace(str, part_to_replace, replace_with) {
return str.replace(part_to_replace, replace_with);
}
console.log(str_replace("amir", "ir", "er"));
console.log(check("amir", str_replace("amir", "ir", "er")));
It looks like you want an array of characters in the new string that were not present in the old one. This will do the trick:
function getDifference(oldStr, newStr) {
// .split('') turns your string into an array of characters
var oldSplit = oldStr.split('');
var newSplit = newStr.split('');
// then compare the arrays and get the difference
var diff = [];
for (var i = 0; i < newSplit.length; i++) {
if (newSplit[i] !== oldSplit[i]) {
diff.push(newSplit[i]);
}
}
return diff;
}
var diff = getDifference('amir', str_replace('amir', 'ir', 'er'));
console.log(diff); // e

How To Change What You've Called In A Function To An Array

Suppose I create a function that flips an array's elements. For example, the function takes in [1,2,3,4] and flips it to [4,3,2,1]. My function is capable of doing that. However, I want to do something that doesn't seem to work. If I call the function like this: flip("hello"), I want it to change "hello" to an array like this: [h,e,l,l,o], flip the elements to become like this: o,l,l,e,h then join the elements together to make it olleh. This is what I have been able to make so far:
function reverse (A) {
if(typeof(A) == 'string') { A.toString().split(" "); }
var i1 = 0;
var i2 = A.length - 1;
function swap(A, i1, i2) {
var temp = A[i1];
A[i1] = A[i2];
A[i2] = temp;
return A;
}
var index1 = 0;
var index2 = A.length - 1;
var temp = A[index1];
for(let i = index1; i < index2; i++) {
swap(A, i, index2); index2--;
}
console.log(A);
}
This does not work at all. I think that is because I am not dealing with what is being called but rather the parameter itself. I have also tried:
if(typeof(reverse(A)) == 'string') {A.toString().split(" "); }
However, that gives me a result that says: RangeError: Maximum call stack size exceeded
I have been searching for an hour with no success. Any help?
Replace
A.toString().split(" ");
with
A = A.split(""); // empty string for splitting, splits every character
because you need an assignment and while A is already an string, you do not need toString().
Later you have to return the joined array with:
return A.join('');
Methods used:
String.prototype.split()
The split() method splits a String object into an array of strings by separating the string into substrings.
Array.prototype.join()
The join() method joins all elements of an array into a string.
Complete working code with some minor changes:
function reverse(a) {
function swap(b, i1, i2) {
var temp = b[i1];
b[i1] = b[i2];
b[i2] = temp;
}
var index1 = 0,
index2 = a.length - 1,
isString = typeof a === 'string';
if (isString) {
a = a.split("");
}
for (index1 = 0; index1 < index2; index1++) {
swap(a, index1, index2);
index2--;
}
return isString ? a.join('') : a;
}
document.write('<pre>' + JSON.stringify(reverse([100, 101, 102]), 0, 4) + '</pre>');
document.write('<pre>' + JSON.stringify(reverse('hello'), 0, 4) + '</pre>');
<pre><code>
<script>
function myFunction() {
var str = "hello";
var splitting = str.split("");
var reversed_array=splitting.reverse();
var result=reversed_array.join("");
document.getElementById("demo").innerHTML = result;
}
</script>
</code></pre>
Function that are used
split :- which will split the string into array .
reverse :- which will be used to reverse the array .
join :- It will join the reversed array
javascript stringarrayfunction

How to search an array in Jquery like SQL LIKE value% statement [duplicate]

This question already has answers here:
How to check if a string "StartsWith" another string?
(18 answers)
Closed 9 years ago.
I have an array with some values. How can I search that array using jQuery for a value which is matched or close to it?
var a = ["foo","fool","cool","god","acl"];
If I want to search for c, then it should return cool but not acl.
How I can achieve that?
Try this:-
arr = jQuery.grep(a, function (value) {
search = /c/gi;
if(value.match(search)) return true;
return false;
});
or
function find(arr) {
var result = [];
for (var i in arr) {
if (arr[i].match(/c/)) {
result.push(arr[i]);
}
}
return result;
}
window.onload = function() {
console.log(find(["foo","fool","cool","god","acl"]));
};
Use substring to check if each string in the array begins with the string you are searching for:
var strings = [ "foo", "cool", "acl" ];
var needle = "c";
for (var i = 0; i < strings.length; ++i) {
if (strings[i].substring(0, needle.length) === needle) {
alert("found: " + strings[i]);
}
}
A simple way to do it is to check for words starting with 'c' and iterate of the array.
var ar = ['acl','cool','cat']
for(var i = 0 ; i<ar.length ; i++){
console.log(ar[i].match(/^c/))
}
//Prints:
//null
//["c", index: 0, input: "cool"]
//["c", index: 0, input: "cat"]
You can use the filter method which is available since JavaScript 1.6. It will give you back an array with the filtered values. Very handy if you want to match multiple items.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
var a = ["foo","fool","cool","god","acl"];
var startsWith = 'c';
a.filter(function (value) {
return value && value.length > 0 && value[0] == startsWith;
});
// yields: ["cool"]
var a = ["foo","fool","cool","god","acl"];
var Character="f";
for(i=0;i<a.length;i++){
if(a[i].indexOf(Character)!=-1){
document.write(a[i]+"<br/>");
}
}

Extract specific substring using javascript?

If I have the following string:
mickey mouse WITH friend:goofy WITH pet:pluto
What is the best way in javascript to take that string and extract out all the "key:value" pairs into some object variable? The colon is the separator. Though I may or may not be able to guarantee the WITH will be there.
var array = str.match(/\w+\:\w+/g);
Then split each item in array using ":", to get the key value pairs.
Here is the code:
function getObject(str) {
var ar = str.match(/\w+\:\w+/g);
var outObj = {};
for (var i=0; i < ar.length; i++) {
var item = ar[i];
var s = item.split(":");
outObj[s[0]] = s[1];
}
return outObj;
}
myString.split(/\s+/).reduce(function(map, str) {
var parts = str.split(":");
if (parts.length > 1)
map[parts.shift()] = parts.join(":");
return map;
}, {});
Maybe something like
"mickey WITH friend:goofy WITH pet:pluto".split(":")
it will return the array, then Looping over the array.
The string pattern has to be consistent in one or the other way atleast.
Use split function of javascript and split by the word that occurs in common(our say space Atleast)
Then you need to split each of those by using : as key, and get the required values into an object.
Hope that's what you were long for.
You can do it this way for example:
var myString = "mickey WITH friend:goofy WITH pet:pluto";
function someName(str, separator) {
var arr = str.split(" "),
arr2 = [],
obj = {};
for(var i = 0, ilen = arr.length; i < ilen; i++) {
if ( arr[i].indexOf(separator) !== -1 ) {
arr2 = arr[i].split(separator);
obj[arr2[0]] = arr2[1];
}
}
return obj;
}
var x = someName(myString, ":");
console.log(x);

Categories

Resources