string method exact text - javascript

So, I am brand spanking new to JavaScript. I am practicing right now with a Codeacedemy tutorial, and it had me create a program that finds my name in a string of text. But, I realized that if I use a name thats similiar to mine, it will return the other name too. What method can I use or how can I refine the code so that it will only match the exact name in the string?
Here's the code:
/*jshint multistr:true */
var text = "Hello my name is Zachary Sohovich. I'm a 20 year old dude from Southern California and I love to code";
var myName = "Zachary";
var hits = [];
for (var i = 0; i < text.length; i++){
if (text[i] == 'Z') {
for (var j = i;j < (i + myName.length); j++) {
hits.push(text[j]);
}
}
}
if (hits === 0) {
console.log("Your name was not found!");
}
else {
console.log(hits);
}

You could String.split the string at the white spaces to create an array of words and then check each word against your test string, thus preventing matches within a substring. (with an alternative loop while)
Javascript
var text = "Hello my name is Zachary Sohovich. I'm a 20 year old dude from Southern California and I love to code",
myName = "Zachary",
hits = 0,
array = text.split(/\s/),
length = array.length,
i = 0;
while (i < length) {
if (myName === array[i]) {
hits += 1;
}
i += 1;
}
if (hits === 0) {
console.log("Your name was not found!");
} else {
console.log(hits);
}
On jsfiddle
Or if you really want to have fun with checking the string by loops then you could do something like this.
Javascript
var text = "Zachary Hello my name is Zachary Sohovich. I'm a 20 year old dude from ZacharySouthern California and I loZacharyve to code Zachary",
textLength = text.length,
myName = "Zachary",
nameLength = myName.length,
check = true,
hits = 0,
i = 0,
j;
while (i < textLength) {
if (check) {
if (i !== 0) {
i += 1;
}
j = 0;
while (j < nameLength) {
if (text.charAt(i + j) !== myName.charAt(j)) {
break;
}
j += 1;
}
if (j === nameLength && (/\s/.test(text.charAt(i + j)) || i + j === textLength)) {
hits += 1;
i += j;
}
}
i += 1;
check = /\s/.test(text.charAt(i));
}
if (hits === 0) {
console.log("Your name was not found!");
} else {
console.log(hits);
}
On jsfiddle
Note: there are a number of other possible solutions that will do the same for you.

**
for(var i = 0; i < text.length ; i++){
if(text[i] === "Z"){
var getText = text.substring(i, i + myName.length);
if(getText === myName)
{
for(var j = i; j < (myName.length + i); j++){
hits.push(text[j]);
}
}
}
}
**
It'll do... easy one.

You need not do all those stuff.
Just find your name with following code
if(text.indexOf(myName) !== -1){
console.log('Found');
}
If its the total number of occurrences you would like to find
var count = text.match(/Zachary/g).length;
console.log(count)

Here's my enhanced version of that lesson.
/*jshint multistr:true */
var text = "Anastasius is known to have had a brother named Flavius Paulus, who served \
asRoman consul in 496. A sister-in-law, known as Magna, was mother to Irene and \
mother-in-law to Olybrius. This Olybrius was son of Anicia Juliana and Areobindus \
Dagalaiphus Areobindus. The daughter of Olybrius and Irene was named Proba. She \
married Probus and was mother to a younger Juliana. This younger Juliana married another \
Anastasius and was mother of Areobindus, Placidia, and a younger Proba. Another nephew \
of Anastasius was Flavius Probus, Roman consul in 502. Caesaria, sister of Anastasius, \
married Secundinus. They were parents to Hypatius and Pompeius. Flavius Anastasius \
Paulus Probus Moschianus Probus Magnus, Roman Consul in 518 also was a great-nephew of \
Anastasius. His daughter Juliana later married Marcellus, a brother of Justin II. The \
extensive family may well have included viable candidates for the throne.";
var textAsWords = text.split(/\s/);
var myName = "Anastasius";
var hits = [];
for (var i = 0; i < textAsWords.length; i++) {
if (myName === textAsWords[i]) {
hits.push(textAsWords[i]);
}
}
if (hits === 0) {
console.log("Your name was not found!");
} else {
console.log(hits);
}

This is what I came up with, staying close to the original exercise.
This consisted of comparing each letter in the text to the first character of the name. On finding that character, you had to add it and any characters that followed into an array, only stopping when the number of characters were equal to the number of letters in the name.
Next, the student was asked to improve the code so it would only add letters matching the exact name. Because the original exercise did not use whitespace or searching for an occurence of the name in one complete string of letters, I did not either.
/*jshint multistr:true */
var text = "olleboleYntke Mchael MichaetMichael S1knol E E rin oef goblinMichael kdmS3ksMichael K elkekeerifdlkùYnyslght MichaelSerind";
myName = "Michael";
var hits = [];
var getCharName = function(namePos) {
charName = myName[namePos];
};
for (i = 0; i <= text.length; i++) {
namePos = 0;
getCharName(namePos);
if (text[i] === charName) {
var letterMatch = false;
for (j = 0; j < myName.length; j++) {
getCharName((namePos + j));
if (text[(i + j)] === charName) {
letterMatch = true;
} else {
letterMatch = false;
}
}
if (letterMatch === true) {
for (j = 0; j < myName.length; j++) {
hits.push(text[(i + j)]);
}
}
}
}
if (hits === 0) {
console.log("Your name was not found!");
} else {
console.log(hits);
}

I'm on the same exercise, and this is my answer.
The method first finds a match with the first letter of myName. When we find a match, we place a X marker on it and run down the text to see if there is a full match. If there is a full match, we return to the X marker and place the correct length of text into the output array "hits". After placing all the letters into the array, we return to the X marker to continue with the rest of the text.
If we don't have a full match, we return to our X spot and continue on to find a match with the first letter of myName again.
var text = "HahahnhahahahnhaHahahahahahahahahahahahaHahahahahahahahahahaHahahahahahnhaHahnhahahahahahahahahaHahaha"
var myName = "Hahn"
var hits =[] //the output will be an array
for(i=0; i<text.length; i++){
var m = 0;
if(text[i] === myName[0]){
for (j=0; j<myName.length; j++){
if (text[i+j] !== myName[m]){
break
}
m++;
if (m === myName.length){
for (n=0; n<myName.length; n++){
hits.push(text[i+n]);
}
}
}
}
}
console.log(hits)

The shortest way of finding your name is to use .match example below:
var text = "Hello my name is Zachary Sohovich. I'm a 20 year old dude from
Southern California and I love to code";
var nameCheck = text.match(/zachary/gi)
console.log(nameCheck)
Note that THE gi after your name this tells the console to log all matches irrespective of case to use. You can also use .match to also be case sensitive by replacing gi with g.

Related

Adding method to prototype string but want does this method mean

I am trying to understand what this mean?
What I am thinking is that phrase will pass a part of array, so this in this case eve to phrase.palindrome method. That method will take and run it through. First var len takes eve and remove 1 from it using length -1. This results in var len being assigned number two as the length of eve is 3. Now for is in use, so var i = 0; i <= len/2; i++.
now becomes var i = 1;1 <= 1; i++."is this correct"
I don't understand what going on here:
for (var i = 0; i <= len/2; i++) {
if (this.charAt(i) !== this.charAt(len-i)) {
return false;
Here is all of the the code:
String.prototype.palindrome = function() {
var len = this.length-1;
for (var i = 0; i <= len/2; i++) {
if (this.charAt(i) !== this.charAt(len-i)) {
return false;
}
}
return true;
};
var phrases = ["eve", "kayak", "mom", "wow", "Not a palindrome"];
for (var i = 0; i < phrases.length; i++) {
var phrase = phrases[i];
if (phrase.palindrome()) {
console.log("'" + phrase + "' is a palindrome");
} else {
console.log("'" + phrase + "' is NOT a palindrome");
}
}
The code is essentially iterating through the string from both directions, comparing the first and last characters (indexes 0 and len) then the second from first and second from last and so forth until you reach the middle. A word is a palindrome if and only if the first and last characters are the same and the second and second to last characters are the same and so forth.
Note, there is something very wrong with this code. While it is technically possible to mutate the prototypes of built-in types in Javascript you should never, ever, ever do it. You gain no functionality you wouldn't from a normal function, while badly violating the principle of least surprise. Treat all types from other libraries, including built ins as if they are closed for modification and open for extension.
I think this line has error:
for (var i = 0; i <= len/2; i++) {
Beacuse somethimes length can be 3,5,7... and that can be problem.
I added some using examples:
for (var i = 0; i <= Math.floor(len / 2); i++) {
// That same thing with floor in positive numbers, but in negative numbers that works like ceil.
for (var i = 0; i <= ~~(len / 2); i++) {
// That same thing with floor, we can think like this pollyfill of floor.
for (var i = 0; i <= ~~(len / 2) + (Math.abs(len)>len?-1:0); i++) {

Javascript - Fastest search for a word in array of string (not full match also)

I am coding search on a webpage which searchs all files, which the webpage consists of.
I iterate through every file and save all words to array of strings.
For example: var array = ["these","are","some","random","words","on","a","webpage"]
The search engine works this way: e.g. user type "s" and if any word from array contains this letter, the word is displayed as a result. In this case the results would be: "these", "some", "words"
The problem is that I have like 30 files in which I search and in each file there is on average 500 words so the search is slow.
letter search (e.g. "s") ~ 4 seconds
letter search (e.g. "se") ~ 2.1 seconds
letter search (e.g. "sea") ~ 1.9 seconds
letter search (e.g. "sear") ~ 1.7 seconds...
I iterate through the array with for-cycle and I think that is the biggest problem. So what is the fastest way to find if searched word is in array of strings and compare also not full matches?
EDIT:
On the webpage it looks like this e.g.:
Searched word: "sear"
Results:
Intro (name of page; clickable url link)
...you can search in this page... (sentence with words around the searched word)
Code explanation:
iterating through files
remove html characters and other special characters and save words from file to array of strings
compare words from file with words which user search for
save sentence with the searched word to a sentence variable
save sentence to an object (this object is later iterated in .html file and the sentences are displayed at webpage)
words typed by user which are going to be searched are in variable words
Here is my code.
var searchIndexPromise;
var searchAppModule = angular.module("searchApp", []);
searchAppModule.run(function($rootScope, $http){
var globalSearch = $rootScope.globalSearch = {
query: "",
results: [],
open: function(){
window.location.href = "#!/51_00_Search";
globalSearch.search(globalSearch.query);
},
search: function(find) {
if(!searchIndexPromise) searchIndexPromise = $http.get("searchIndex.json").then(function(response){
return response.data;
});
console.log("searching", find);
searchIndexPromise.then(function(searchIndex){
var temp = [];
globalSearch.results = [];
var words = find.split(' ');
if (words < 1) {
return;
}
for (var key in searchIndex) {
for (var option in searchIndex[key]) {
for(var i=0; i < words.length; i++) {
if (key.includes(words[i].toLowerCase())) {
var name = searchIndex[key][option].name;
var page = searchIndex[key][option].page;
var word = words[i];
var count = 0;
for (var j = 0; j < temp.length; j++) {
if (temp[j].name == name && temp[j].word == word) {
break;
}
count++;
}
if (count == temp.length) {
temp.push({ name : name, page : page, word : word });
}
}
}
}
}
if (words.length < 2) {
globalSearch.results = temp;
}
else {
for (var i = 0; i < temp.length; i++) {
var count = 0;
var compare = temp[i];
for (var j = 0; j < temp.length; j++) {
if (compare.name == temp[j].name) {
if (globalSearch.results.indexOf(temp[j]) == -1) {
count++;
}
}
}
if (count == words.length) {
globalSearch.results.push(temp[i]);
}
}
}
//sentences
const pagesLoad = require("./pages.js");
globalSearch.pages = [];
for (var result in globalSearch.results) {
var page = globalSearch.results[result].page.substring(3);
if ((page + ".html" in pagesLoad)) {
var nameOfPage = page + ".html";
}
if ((page + ".md" in pagesLoad)) {
var nameOfPage = page + ".md";
}
var regex = /(<([^>]+)>)|\n|\#|\(|\)|\*|\-|[^\w\s!?]|\n| +(?= )/ig, data = pagesLoad[nameOfPage].src.replace(regex, " ");
var string = data.split(" ");
string = string.filter(Boolean);
let lowerString = string.map((item) => {
return item.toLowerCase();
});
//this part is slowing down the search
for (var i = 0; i < lowerString.length; i++) {
for (var j = 0; j < words.length; j++) {
if (lowerString[i].includes(words[j].toLowerCase())) {
var sentence = "...";
for (var k = i - 6; k < i + 6; k++) {
if (lowerString[k] == null) {
continue;
}
sentence = sentence + string[k] + " ";
}
sentence = sentence.slice(0, -1);
sentence += "...";
globalSearch.pages.push({page: globalSearch.results[result].page, sentence: sentence});
}
}
}
}
})
}
};
});

hangman --can't get my loop to display correct answers

First day of school, we're supposed to make a hangman game. I've been staring at the logic in my while loop for hours now. I can't get my loop to say yes, the word(newWord) does contain the guess. I always get the prompt that it is incorrect, and then all heck breaks loose. I've tried 25 different ways. I know it's all busted beyond repair now, but if anyone can get me going the right direction, I'd be eternally grateful.
let words = ["skate", "guitar", "laugh", "party", "shirt"]
let wordValue = Math.floor(Math.random() * 4) + 1;
let newWord = words[wordValue];
let misses = 0;
let rightGuess = 0;
let wrongGuess = 0;
var answerLines = [];
for (let i = 0; i < newWord.length; i++) {
answerLines[i] = "_";
}
let remainingLetters = newWord.length;
while (remainingLetters > 0 && misses < 6) {
alert(answerLines.join(" "));
let guess = prompt("Guess a letter, any letter!");
for(let j = 0; j < newWord.length; j++) {
if (newWord[j] === guess) {
rightGuess++
}
else { wrongGuess++ }
if (rightGuess != 0) {
answerLines[j] = guess;
remainingLetters--;
}
else {
misses++
(alert("That was is incorrect. You have " + misses + " of 6 misses."));
Your logic for processing the guess is a little off. Try this:
var words = ["skate", "guitar", "laugh", "party", "shirt"]
var wordValue = Math.floor(Math.random() * 4) + 1;
var newWord = words[wordValue];
console.log("Word is: " + newWord);
var misses = 0;
var answerLines = [];
for (var i = 0; i < newWord.length; i++) {
answerLines[i] = "_";
}
var remainingLetters = newWord.length;
while (remainingLetters > 0 && misses < 6) {
alert(answerLines.join(" "));
var guess = prompt("Guess a letter, any letter!");
var matchesNone = true; //boolean to track if guess matched any letters
for (var j = 0; j < newWord.length; j++) {
if (newWord[j] === guess) {
answerLines[j] = guess;
remainingLetters--;
matchesNone = false; //the guess matched atleast one letter
}
}
if (matchesNone) { //the guess matched none of the letters
misses ++;
alert("That was is incorrect. You have " + misses + " of 6 misses.");
}
}
if(remainingLetters>0) {
alert("You failed to guess the word: " + newWord);
}else{
alert("You guessed the word! It was: " + newWord);
}

Showing unique characters in a string only once

I have a string with repeated letters. I want letters that are repeated more than once to show only once.
Example input: aaabbbccc
Expected output: abc
I've tried to create the code myself, but so far my function has the following problems:
if the letter doesn't repeat, it's not shown (it should be)
if it's repeated once, it's show only once (i.e. aa shows a - correct)
if it's repeated twice, shows all (i.e. aaa shows aaa - should be a)
if it's repeated 3 times, it shows 6 (if aaaa it shows aaaaaa - should be a)
function unique_char(string) {
var unique = '';
var count = 0;
for (var i = 0; i < string.length; i++) {
for (var j = i+1; j < string.length; j++) {
if (string[i] == string[j]) {
count++;
unique += string[i];
}
}
}
return unique;
}
document.write(unique_char('aaabbbccc'));
The function must be with loop inside a loop; that's why the second for is inside the first.
Fill a Set with the characters and concatenate its unique entries:
function unique(str) {
return String.prototype.concat.call(...new Set(str));
}
console.log(unique('abc')); // "abc"
console.log(unique('abcabc')); // "abc"
Convert it to an array first, then use Josh Mc’s answer at How to get unique values in an array, and rejoin, like so:
var nonUnique = "ababdefegg";
var unique = Array.from(nonUnique).filter(function(item, i, ar){ return ar.indexOf(item) === i; }).join('');
All in one line. :-)
Too late may be but still my version of answer to this post:
function extractUniqCharacters(str){
var temp = {};
for(var oindex=0;oindex<str.length;oindex++){
temp[str.charAt(oindex)] = 0; //Assign any value
}
return Object.keys(temp).join("");
}
You can use a regular expression with a custom replacement function:
function unique_char(string) {
return string.replace(/(.)\1*/g, function(sequence, char) {
if (sequence.length == 1) // if the letter doesn't repeat
return ""; // its not shown
if (sequence.length == 2) // if its repeated once
return char; // its show only once (if aa shows a)
if (sequence.length == 3) // if its repeated twice
return sequence; // shows all(if aaa shows aaa)
if (sequence.length == 4) // if its repeated 3 times
return Array(7).join(char); // it shows 6( if aaaa shows aaaaaa)
// else ???
return sequence;
});
}
Using lodash:
_.uniq('aaabbbccc').join(''); // gives 'abc'
Per the actual question: "if the letter doesn't repeat its not shown"
function unique_char(str)
{
var obj = new Object();
for (var i = 0; i < str.length; i++)
{
var chr = str[i];
if (chr in obj)
{
obj[chr] += 1;
}
else
{
obj[chr] = 1;
}
}
var multiples = [];
for (key in obj)
{
// Remove this test if you just want unique chars
// But still keep the multiples.push(key)
if (obj[key] > 1)
{
multiples.push(key);
}
}
return multiples.join("");
}
var str = "aaabbbccc";
document.write(unique_char(str));
Your problem is that you are adding to unique every time you find the character in string. Really you should probably do something like this (since you specified the answer must be a nested for loop):
function unique_char(string){
var str_length=string.length;
var unique='';
for(var i=0; i<str_length; i++){
var foundIt = false;
for(var j=0; j<unique.length; j++){
if(string[i]==unique[j]){
foundIt = true;
break;
}
}
if(!foundIt){
unique+=string[i];
}
}
return unique;
}
document.write( unique_char('aaabbbccc'))
In this we only add the character found in string to unique if it isn't already there. This is really not an efficient way to do this at all ... but based on your requirements it should work.
I can't run this since I don't have anything handy to run JavaScript in ... but the theory in this method should work.
Try this if duplicate characters have to be displayed once, i.e.,
for i/p: aaabbbccc o/p: abc
var str="aaabbbccc";
Array.prototype.map.call(str,
(obj,i)=>{
if(str.indexOf(obj,i+1)==-1 ){
return obj;
}
}
).join("");
//output: "abc"
And try this if only unique characters(String Bombarding Algo) have to be displayed, add another "and" condition to remove the characters which came more than once and display only unique characters, i.e.,
for i/p: aabbbkaha o/p: kh
var str="aabbbkaha";
Array.prototype.map.call(str,
(obj,i)=>{
if(str.indexOf(obj,i+1)==-1 && str.lastIndexOf(obj,i-1)==-1){ // another and condition
return obj;
}
}
).join("");
//output: "kh"
<script>
uniqueString = "";
alert("Displays the number of a specific character in user entered string and then finds the number of unique characters:");
function countChar(testString, lookFor) {
var charCounter = 0;
document.write("Looking at this string:<br>");
for (pos = 0; pos < testString.length; pos++) {
if (testString.charAt(pos) == lookFor) {
charCounter += 1;
document.write("<B>" + lookFor + "</B>");
} else
document.write(testString.charAt(pos));
}
document.write("<br><br>");
return charCounter;
}
function findNumberOfUniqueChar(testString) {
var numChar = 0,
uniqueChar = 0;
for (pos = 0; pos < testString.length; pos++) {
var newLookFor = "";
for (pos2 = 0; pos2 <= pos; pos2++) {
if (testString.charAt(pos) == testString.charAt(pos2)) {
numChar += 1;
}
}
if (numChar == 1) {
uniqueChar += 1;
uniqueString = uniqueString + " " + testString.charAt(pos)
}
numChar = 0;
}
return uniqueChar;
}
var testString = prompt("Give me a string of characters to check", "");
var lookFor = "startvalue";
while (lookFor.length > 1) {
if (lookFor != "startvalue")
alert("Please select only one character");
lookFor = prompt(testString + "\n\nWhat should character should I look for?", "");
}
document.write("I found " + countChar(testString, lookFor) + " of the<b> " + lookFor + "</B> character");
document.write("<br><br>I counted the following " + findNumberOfUniqueChar(testString) + " unique character(s):");
document.write("<br>" + uniqueString)
</script>
Here is the simplest function to do that
function remove(text)
{
var unique= "";
for(var i = 0; i < text.length; i++)
{
if(unique.indexOf(text.charAt(i)) < 0)
{
unique += text.charAt(i);
}
}
return unique;
}
The one line solution will be to use Set. const chars = [...new Set(s.split(''))];
If you want to return values in an array, you can use this function below.
const getUniqueChar = (str) => Array.from(str)
.filter((item, index, arr) => arr.slice(index + 1).indexOf(item) === -1);
console.log(getUniqueChar("aaabbbccc"));
Alternatively, you can use the Set constructor.
const getUniqueChar = (str) => new Set(str);
console.log(getUniqueChar("aaabbbccc"));
Here is the simplest function to do that pt. 2
const showUniqChars = (text) => {
let uniqChars = "";
for (const char of text) {
if (!uniqChars.includes(char))
uniqChars += char;
}
return uniqChars;
};
const countUnique = (s1, s2) => new Set(s1 + s2).size
a shorter way based on #le_m answer
let unique=myArray.filter((item,index,array)=>array.indexOf(item)===index)

Javascript string matching pattern help

i need to find few words or matching pattern using a Javascript.
this is the requirement.
i have a string like this,
Here is a quick guide for the next
time you reach for your favorite oil and some other topics
and i need to match this string against a string like this
favorite oil and some other topics can be based on something blah blah
how do i get the intersection of matching text blocks?
I already tried intersect Javascript script function, for some strings it's not working properly.
How to solve this problem? can this be done using Regex?
Please advice.
You have to find the Longest common substring.
If the strings are not very long, I recommend using Tim's approach. Otherwise, this is a Javascript implementation of the Longest common substring algorithm with dynamic programming. The runtime is O(mn) where m and n are the lengths of the 2 strings respectively.
An example usage:
var first = "Here is a quick guide for the next time you reach for your favorite oil and some other topics";
var second = "favorite oil and some other topics can be based on something blah blah";
console.log(first.intersection(second)); // ["favorite oil and some other topic"]
This is the algorithm implementation. It returns an array of the longest common substring(s). Extended the native String class, so the intersect method is available on all strings.
String.prototype.intersection = function(anotherString) {
var grid = createGrid(this.length, anotherString.length);
var longestSoFar = 0;
var matches = [];
for(var i = 0; i < this.length; i++) {
for(var j = 0; j < anotherString.length; j++) {
if(this.charAt(i) == anotherString.charAt(j)) {
if(i == 0 || j == 0) {
grid[i][j] = 1;
}
else {
grid[i][j] = grid[i-1][j-1] + 1;
}
if(grid[i][j] > longestSoFar) {
longestSoFar = grid[i][j];
matches = [];
}
if(grid[i][j] == longestSoFar) {
var match = this.substring(i - longestSoFar + 1, i);
matches.push(match);
}
}
}
}
return matches;
}
Also need this helper function to create a 2d array with all elements initialize to 0.
// create a 2d array
function createGrid(rows, columns) {
var grid = new Array(rows);
for(var i = 0; i < rows; i++) {
grid[i] = new Array(columns);
for(var j = 0; j < columns; j++) {
grid[i][j] = 0;
}
}
return grid;
}
This isn't very efficient and there are much better ways to do this in general (see #Anurag's answer), but it's simple and works fine for short strings:
function stringIntersection(str1, str2) {
var strTemp;
// Swap parameters if necessary to ensure str1 is the shorter
if (str1.length > str2.length) {
strTemp = str1;
str1 = str2;
str2 = strTemp;
}
// Start with the whole of str1 and try shorter substrings until
// we have a common one
var str1Len = str1.length, l = str1Len, start, substring;
while (l > 0) {
start = str1Len - l;
while (start >= 0) {
substring = str1.slice(start, l);
if (str2.indexOf(substring) > -1) {
return substring;
}
start--;
}
l--;
}
return "";
}
var s1 = "Here is a quick guide for the next time you reach"
+ " for your favorite oil and some other topics";
var s2 = "favorite oil and some other topics can be based on"
+ " something blah blah";
alert( stringIntersection(s1, s2) );
A simple polyfill of filter a string
if (!String.prototype.intersection) {
String.prototype.intersection = function(anotherString, caseInsensitive = false) {
const value = (caseInsensitive) ? this.toLowerCase() : this;
const comp = (caseInsensitive) ? anotherString.toLowerCase() : anotherString;
const ruleArray = comp.split("").reduce((m,v) => {m[v]=true; return m;} ,{})
return this.split("").filter( (c, i) => ruleArray[value[i]] ).join("")
}
}
"HelloWorld".intersection("HEWOLRLLODo", true)
"HelloWorld" - case insensitive
"HelloWorld".intersection("HEWOLRLLODo")
"HoWo" - case sensitive

Categories