Intersection of characters in two strings - javascript

I have an object with strings in it.
filteredStrings = {search:'1234', select:'1245'}
I want to return
'124'
I know that I can turn it into an array and then loop through each value and test if that value in inside of the other string, but I'm looking for an easier way to do this. Preferably with Lodash.
I've found _.intersection(Array,Array) but this only works with Arrays.
https://lodash.com/docs#intersection
I want to be able to do this without having to convert the object to an array and then loop through each value because this is going to be potentially holding a lot of information and I want it to work as quickly as possible.
Thank you for you help.

Convert one of the strings (search) to a RegExp character set. Use the RegExp with String#match on the other string (select).
Note: Unlike lodash's intersection, the result characters are not unique, so for example 4 can appear twice.
var filteredStrings = {search:'1234', select:'124561234'}
var result = (filteredStrings.select.match(new RegExp('[' + filteredStrings.search + ']', 'g')) || []).join('');
console.log(result);

Related

Obtain arguments from a string seperated by a space and convert an argument in an array format to an array

I have arguments that will be passed by the user for a command. Each argument for a command will be seperated with a space, which will represent a new argument. Example: "arg1 arg2 arg3" converts to ["arg1", "arg2", "arg3"] where the output is a JS array. This can be done with a simple .split(" ").
However, my problem begin when trying to format an array as a command argument. My goal is to allow the user to enter an agument in the format of an array (e.g. Starts with [ may contain multiple elements seperated by a , and ends with a ]) so for example: "arg1 [elem1, elem2] arg3" converts to ["arg1", ["elem1", "elem2"], "arg3"] where the inner and outer array is a JS array.
I have tried using JSON.Parse() however, each element would require the user to have " at the start of each element which is too complex for the user and non essential to be inputting. Also, the elements may not always intend to be a string and may be Boolean, Number or a custom type.
As of currently, this has been my best solution but misses some requirements and also is non functional when an array has a space inside.
s.split(/[\[\]]|\s+/).filter(arg => arg.length > 1);
I have come up with some other solutions but all are missing one thing or another in the required specification set above. A solution that can handle nested arrays would be nice however it is non-essential and could make the solution alot more complex than it needs to be.
Let's assume no funny characters as the input. Also nesting not allowed.
var str = "arg1 [ elem1 , elem2,elem3 ] arg3";
console.log(str)
// removing white spaces from the [ array ]
str = str.replace(/\s*,\s*/g, ',');
str = str.replace(/\[\s*/g, '[');
str = str.replace(/\s*\]/g, ']');
// now split on words
var arr = str.split(/\s+/);
arr = arr.map(function(elem) {
// if begins with [ it is assumed to be an array to be splitted
return elem.charAt(0) == '[' ? elem.slice(1, -1).split(",") : elem;
})
console.log(arr)

How to look for specific letters in a string inside an array with JS?

Say for example I have a array like this
var array = ['Value1', "ThisIsValue2", "AndThisIsValue3"]
I want to be able to check this array to look for the word And but nothing more once it checks all the values and it finds the one with the word And I want it to take that whole value and save it to another variable. How can I do this?
Try this, use array filter with includes:
let result = array.filter(v => v.includes('And'))
As I understood, you want to search in the array the word that contains "And" and return the whole word.
Easy way but not precise: search the word that contains "And" within any place in the string (ex "AndThisIsValue3", "ThisAndThat")
let result = array.find(w => /And/.test(w));
You can define the regular expression that fits fine with your purpose.
The variable result will store the first word that matches the regExp or undefined if no one does. If you need all matches, just use array.filter in the same way.

How to get substring between two same characters in JavaScript?

I have a string value as abc:language-letters-alphs/EnglishData:7844val: . I want to extract the part language-letters-alphs/EnglishData, the value between first : and second :. Is there a way to do it without storing each substrings on different vars? I want to do it the ES6 way.
You can do this two ways easily. You can choose what suits you best.
Using String#split
Use split method to get your desired text.
The split() method divides a String into an ordered list of substrings, puts these substrings into an array, and returns the array. The division is done by searching for a pattern; where the pattern is provided as the first parameter in the method's call.
let str = 'abc:language-letters-alphs/EnglishData:7844val:'.split(':')
console.log(str[1]) //language-letters-alphs/EnglishData
Using String#slice
You can use [ Method but in that you have define the exact indexes of the words you want to extract.
The slice() method extracts a section of a string and returns it as a new string, without modifying the original string.
let str = 'abc:language-letters-alphs/EnglishData:7844val:'
console.log(str.slice(4, 38)) //language-letters-alphs/EnglishData
const str = "abc:language-letters-alphs/EnglishData:7844val:"
const relevantPart = str.split(':')[1]
console.log("abc:language-letters-alphs/EnglishData:7844val:".split(":")[1])

How to use split() to convert 1.18.0-AAA-1 into 1.18.0 js

How to use the javascript split splice slice methods to convert the:
1.18.0-AAA-1 into 1.18.0.
Start with the initial value, determine that the portion you want is before the first hyphen, so use that as the delimiter for the split. Perform the split and then the first portion will be everything up to but not including that first hyphen. You don't need slice or splice for this - just split. Then just add the dot at the end for the trailing dot.
var x="1.18.0-AAA-1";
var y=x.split("-");//splits it at each "-";
var z=y[0]+".";//gives 1.18.0.
however if you are asking to use each of the threeemethods to yield the outcome, then this sounds like homework and you should try doing it on your own. Best way to learn is to try.
Use split to create an array from your string
var str = "1.18.0-AAA-1";
var parts = str.split("-"); // this returns the array ["1.18.0", "AAA", "1"]
Now the easiest way to get what you want is doing:
parts[0];

What is the fastest way to find which of the substrings is present in a string in javascript?

Okay, may be the question was weird.
Let me explain a case in hand. I have 5 names in an array
eg:
var namesArray=['John','Henry','Smith','James','Carl'];
And I also have a string from some other operation which contains one of these strings with a salutation, say Hello John or Mr.John (note that there is no space in the second one).
var returnedName='Howdy,James!';
What I do know is that the returning string will contain only one of the strings in the mentioned namesArray and no more, and I have no knowledge about the surrounding characters the string may have in returnedName.
What is the fastest way to know which of the strings in the namesArray is a substring of returnedName? I was expecting a function which returns the index of the string in namesArray which is a substring of returnedName. Does such an in-built function exist? If not, what would be the fastest (I have a namesArray of about 100k names, say) way to do that?
This seems to be more like a searching problem. Obviously, while searching you do need to make a comparison to match your search term. For this w.r.t. your problem, in JavaScript you can think of Regex and indexOf. But to make it faster for better time complexity you'll have to think of some better search algorithm (Binary Search may be) than a linear iteration over array.
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf, if I understand well your question.
With a for loop indeed...
See Javascript Performance: How come looping through an array and checking every value is faster than indexOf, search and match? or Fastest way to check a string contain another substring in Javascript? for more precisions about performances issues.
There are multiple ways to check if string contains another substring.
var str = "Hello world, welcome to Javascript Coding.";
var n = str.indexOf("welcome");
//Returns Index no 13
var s = "foo";
console.log(s.indexOf("oo") > -1)
//returns true
You could also use string.includes method to achieve the same result
var str = "Hello World, Welcome to Javascript Coding";
console.log(str.includes("Welcome to")); // true
console.log(str.includes("Javascript")); // true
console.log(str.includes("To be", 1)); // false
Reference article How to check if string contains another substring
You have to iterate over the array, checking if the string contains the array value, and if it does, break the loop (as there can be only one) and set a variable :
var containsName = '';
for (var i=0; i<namesArray.length; i++) {
if ( returnedName.indexOf( namesArray[i] ) != -1 ) {
containsName = namesArray[i];
break;
}
}
alert( containsName );
FIDDLE

Categories