search on string with array with javascript - javascript

search on string with array with javascript
i have a string, i need to search on it with array.
for ex.
// that is array what i have
var arr = ['egypt', 'london', 'spain'];
// that is strings what i have
var str = "hello from egypt";
var str2 = "hello from london and spain";
ex. for first string, i need to now if it contain any values from array, and get it.
like : // found one value 'egypt' on str.
like : // found two values 'london, spain' on str2.

You can use includes to see if array elements exist in the string or not
Here's the code that resolves your problem
// that is array what i have
var arr = ['egypt', 'london', 'spain'];
// that is strings what i have
var str1 = "hello from egypt";
var str2 = "hello from london and spain";
function searchWords(str){
var res="";
for(var i=0;i<arr.length;i++){
if (str.includes(arr[i])){
res+= arr[i] +' '
}
}
console.log('found one value '+res )
}
searchWords(str1);
searchWords(str2);

// that is array what i have
var arr = ['egypt', 'london', 'spain'];
// that is strings what i have
var str = "hello from egypt";
var str2 = "hello from london and spain";
function search_in_string(_string, _array){
var out_arr=[];
for(var key in _array){
if(_string.indexOf(_array[key]) !=-1){
out_arr.push(_array[key]);
}
}
return out_arr;
}
console.log(search_in_string(str, arr));
console.log(search_in_string(str2, arr));

Related

JavaScript - Copy item reference of an array

The answer might be obvious but I didn't find out. I have this code :
const arr = ["Hello"];
let currentStr = arr[0];
currentStr += " world";
console.log(currentStr); // prints "Hello world"
console.log(arr); // prints ["Hello"]
I just want to copy the string reference so when I change the currentStr value, it also change its reference in the array (here the first item of the arr array).
const arr = ["Hello"];
let currentStr = arr[0];
currentStr += " world";
console.log(currentStr); // prints "Hello world"
console.log(arr); // expect print ["Hello world"]
In Javascript strings are immutable. I.e. when you make a change to a string behind the scenes Javascript is making a new copy of that string. Arrays are slightly different. You can mutate arrays. I.e. change what they are storing.
To achieve what you want you can use the splice method on the array to replace the 'Hello' string with a new string called 'Hello' + ' World'. Here is the code for it.
const arr = ['Hello']
arr.splice(0,1, arr[0] + ' World')
console.log(arr) // ['Hello World']
See the MDN docs on Arrays, and the splice method.
const arr = ["Hello"];
var currentStr=[];
let newStr= arr[0]+" World";
currentStr.push(newStr)
console.log(currentStr); //
console.log(arr); //
You can do this by re-assigning currentStr to arr[0].
const arr = ["Hello"];
let currentStr = arr[0];
currentStr += " world";
console.log(currentStr); // prints "Hello world"
arr[0] = currentStr;
console.log(arr); // prints ["Hello world"]

Regex for creating an array from String

I have a string as follows
var str = "[series-3,series-5,series-6],[a3,a4,a5],[class a,class b]";
I want to get three arrays from above string as follows
var arr1 = ["series-3","series-5","series-6"];
var arr2 = ["a3","a4","a5"];
var arr3 = ["class a", "class b"];
What regex should I use to achieve this?
Can this be done without regex?
Use String#split() method
var str = "[series-3,series-5,series-6],[a3,a4,a5],[class a,class b]";
// split string based on comma followed by [
var temp = str.split(/,(?=\[)/);
// remove [ and ] from string usning slice
// then split using , to get the result array
var arr1 = temp[0].slice(1, -1).split(',');
var arr2 = temp[1].slice(1, -1).split(',');
var arr3 = temp[2].slice(1, -1).split(',');
console.log(arr1, arr2, arr3);
Or same method with some variation
var str = "[series-3,series-5,series-6],[a3,a4,a5],[class a,class b]";
// Remove [ at start and ] at end using slice
// and then split string based on `],[`
var temp = str.slice(1, -1).split('],[');
// then split using , to get the result array
var arr1 = temp[0].split(',');
var arr2 = temp[1].split(',');
var arr3 = temp[2].split(',');
console.log(arr1, arr2, arr3);
RegEx and String methods can be used. It's better to create an object and store individual arrays inside that object.
var str = "[series-3,series-5,series-6],[a3,a4,a5],[class a,class b]";
// Match anything that is inside the `[` and `]`
var stringsArr = str.match(/\[[^[\]]*\]/g);
// Result object
var result = {};
// Iterate over strings inside `[` and `]` and split by the `,`
stringsArr.forEach(function(str, i) {
result['array' + (i + 1)] = str.substr(1, str.length - 2).split(',');
});
console.log(result);
var str = "[series-3,series-5,series-6],[a3,a4,a5],[class a,class b]";
var stringsArr = str.match(/\[[^[\]]*\]/g);
var result = {};
stringsArr.forEach(function(str, i) {
result['array' + (i + 1)] = str.substr(1, str.length - 2).split(',');
});
console.log(result);
To create the global variables(Not recommended), just remove var result = {}; and replace result by window in the forEach.
I would prefer to do it like this
var str = "[series-3,series-5,series-6],[a3,a4,a5],[class a,class b]",
arrs = str.match(/[^[]+(?=])/g).map(s => s.split(","));
console.log(arrs);
Just for the fun of it, another way where we add the missing quotes and use JSON.parse to convert it to a multidimensional array.
var str = "[series-3,series-5,series-6],[a3,a4,a5],[class a,class b]";
var result = JSON.parse("[" + str.replace(/\[/g,'["').replace(/\]/g,'"]').replace(/([^\]]),/g,'$1","') + "]");
console.log(result[0]);
console.log(result[1]);
console.log(result[2]);

Get length of every element in array - JavaScript

I want to get length of every element in array
my code is
var a = "Hello world" ;
var chars = a.split(' ');
so I will have an array of
chars = ['Hello' , 'world'] ;
but how I can get length of each word like this ?
Hello = 5
world = 5
You can use map Array function:
var lengths = chars.map(function(word){
return word.length
})
ES6 is now widely available (2019-10-03) so for completeness — you can use the arrow operator with .map()
var words = [ "Hello", "World", "I", "am", "here" ];
words.map(w => w.length);
> Array [ 5, 5, 1, 2, 4 ]
or, very succinctly
"Hello World I am here".split(' ').map(w => w.length)
> Array [ 5, 5, 1, 2, 4 ]
The key here is to use .length property of a string:
for (var i=0;i<chars.length;i++){
console.log(chars[i].length);
}
You could create a results object (so you have the key, "hello", and the length, 5):
function getLengthOfWords(str) {
var results = {};
var chars = str.split(' ');
chars.forEach(function(item) {
results[item] = item.length;
});
return results;
}
getLengthOfWords("Hello world"); // {'hello': 5, 'world': 5}
Try map()
var words = ['Hello', 'world'];
var lengths = words.map(function(word) {
return word + ' = ' + word.length;
});
console.log(lengths);
You can use forEach, if you want to keep the words, and the length you can do it like this:
var a = "Hello world" ;
var chars = a.split(' ');
var words = [];
chars.forEach(function(str) {
words.push([str, str.length]);
});
You can then access both the size and the word in the array.
Optionally you could have a little POJO object, for easier access:
var a = "Hello world" ;
var chars = a.split(' ');
var words = [];
chars.forEach(function(str) {
words.push({word: str, length: str.length});
});
Then you can access them like:
console.log(words[0].length); //5
console.log(words[0].word); //"Hello"
Or using map to get the same POJO:
var words = chars.map(function(str) {
return {word: str, length: str.length};
});

string to list in special format in Javascript

I have a string containing comma separated names and optional values that seprated values like this:
var str = "PowerOn:On,ValidLocation, temp:25";
I want to convert it into objects or json that can access to values by name like this:
var a = {"PowerOn":"On", "ValidLocation":"true", "temp":25};
var result = a.PowerOn;
alert(result);
OR
var a = {"PowerOn":"On", "ValidLocation":"true", "temp":25};
var result = a["PowerOn"];
alert(result);
Note 1: If a name doesn't have value it be true by default.
Update:
Note 2 :If a name doesn't exist in list the value of it be false: ex:
var a = {"PowerOn":"On", "ValidLocation":"true", "temp":25};
var result = a.Alarm
//result must be false
var str = "PowerOn:On,ValidLocation, temp:25",
arr = str.split(','),
obj = {}
for (var i=0; i<arr.length; i++) {
var parts = arr[i].split(':');
obj[parts[0]] = parts[1] || true;
}
JSFIDDLE
Assuming the delimiters remain as such, Does this work for you :
var result = {};
"PowerOn:On,ValidLocation, temp:25".split(",").forEach(function(i) {
result[(i=i.split(":"))[0]]=i[1] || true;
});
// result : {PowerOn: "On", ValidLocation: true, temp: "25"}
To the second part of you question use !!result.Alarm which should be false.

how to split function in javascript

i have data in
var description="Name:John;EmployeeID:2;Salary:$8000;Address:London";
i want the result as
Name: John
Employee Id: 2
Salary: $8000
Address: London
is it possible with split() function in javascript?
You can do it with String.split() but in this case it's simpler to use String.replace():
var description="Name:John;EmployeeID:2;Salary:$8000;Address:London";
description = description.replace(/;/g, '\n').replace(/:/g, ': ');
/*
"Name: John
EmployeeID: 2
Salary: $8000
Address: London"
*/
If you want the result as an object, try:
var f = function (str) {
var x = {}, key2label = { EmployeeID: 'Employee Id' };
str.replace(/(.+?):(.+?)(;|$)/g, function (match, key, value) {
key = key2label[key] || key;
x[key] = value;
});
return x;
};
If a simple string is needed, but you still need to replace keys:
var f2 = function (str) {
var key2label = { EmployeeID: 'Employee Id' };
return str.replace(/(.+?):(.+?)(;|$)/g, function (match, key, value, semi) {
key = key2label[key] || key;
return key + ': ' + value + (semi ? '\n' : '');
});
};
If you really didn't mean to replace keys, this will do it:
var f3 = function (str) {
return str.split(':').join(': ').split(';').join('\n');
};
... or use Matt Ball's answer.
With this statement:
var arrDescription = description.split(";");
you will get an array with all the values. For more info on split check the following link.
you can even join them afterwards :
printf(arrDescription.join(" "));
For more info on join check the following link.
Max
You can probable try like this to display.
var description="Name:John;EmployeeID:2;Salary:$8000;Address:London";
var arr=new Array();
arr=description.split(";");
for(var i=0;i<arr.length;i++)
document.writeln("<h4>"+arr[i]+"</h4>");
Yes.
You first should split on the semicolon ;. Loop through those results, and split each result on each colon :.
You will have to build the result by hand.
var description="Name:John;EmployeeID:2;Salary:$8000;Address:London"; var splitted = description.split(";");
for(var i = 0; i < splitted.length; i++) { document.write(splitted[i] + ""); }

Categories