Finding ALL positions of a string within another string [duplicate] - javascript

This question already has answers here:
How can I match overlapping strings with regex?
(6 answers)
JS Match all occurrences of substring in a string
(2 answers)
Closed 3 years ago.
I can't find out a solution to the following problem and it's driving me nuts. I need to find every position of a string within another string.
This is what I have come up with:
function getMatchIndices(regex, str) {
let result = [];
let match;
let regex = new RegExp(regex, 'g');
while (match = regex.exec(str))
result.push(match.index);
return result;
}
const line = "aabaabbaababaababaaabaabaaabaabbabaababa";
const rule = 'aba';
const indices = getMatchIndices(new RegExp(rule, "g"), line);
console.log(indices);
Now, the issue is that this does NOT match aba's that are formed in the middle of two other matches...
Here is an image illustrating the problem:
Any ideas?

I realize this is NOT a Regex solution. So it might not be what you need.
Hope it helps.
function getMatchIndices(r, str) {
const indices = [];
str.split('').forEach((v,i) => {
if(r === str.substring(i,i+r.length)) {
indices.push(i);
}
});
return indices;
}
const line = "aabaabbaababaababaaabaabaaabaabbabaababa";
const rule = 'aba';
const indices = getMatchIndices(rule, line);
console.log(indices);

Related

How to check if string has vowels? [duplicate]

This question already has answers here:
Counting the vowels in a string using Regular Expression
(2 answers)
Closed 1 year ago.
I tried to write a function which checks if a given string contains vowels and I cannot see why it works for some words 'cat' and 'why' but not 'DOG', i believe that i have accounted for uppercase.
const containsVowels = string => {
var lowerCase = string.toLowerCase();
var word = lowerCase.split("");
var vowelsArray = ["a","o","i","u","y"];
const result = word.filter(letter => vowelsArray.includes(letter));
return result.includes("a","o","i","u","y");
};
includes takes only 2 parameters, the first one being searchElement and second parameter being fromIndex.
Reference : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes#parameters
You wouldn't want to do the last check if the result array contains vowels or not, because in the previous step itself you are filtering out the word to get array that contains only vowels. So just check if the array is empty or it contains any elements inside it.
const containsVowels = str => {
let lowerCase = str.toLowerCase();
let word = lowerCase.split("");
let vowelsArray = ["a","o","i","u","y"];
const result = word.filter(letter => vowelsArray.includes(letter));
return result.length > 0;
};
console.log(containsVowels("cat"));
console.log(containsVowels("DOG"));
console.log(containsVowels("BCDF"));
Suggestion: Don't use built in keywords as variables.
As pointed out by Muhammad, we can regex to find if the string contains vowels
const containsVowel = str => {
const vowelRegex = /[aeiou]/i;
return vowelRegex.test(str);
};
2 Problems,
Why would you use includes twice ?
&
You cannot use includes like
result.includes("a","o","i","u","y");
includes only accepts 2 param:
includes(searchElement, fromIndex)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes
By filtering, you already know the result.
What you should do is, compare the length of the result:
const containsVowels = string => {
let lowerCase = string.toLowerCase();
let word = lowerCase.split("");
let vowelsArray = ["a","o","i","u","y"];
const result = word.filter(letter => vowelsArray.includes(letter));
return result.length > 0 ? true : false
};
use regex to get the result.
var regEx = /[aeiou]/gi
var test_string = "Cat";
var match = test_string.match(regEx)
if(match)
console.log("Match found", match)
when you write something like this
result.includes("a","o","i","u","y")
this compare with only it's first element which is "a" and one thing you don't need to write the above mentioned code further.
After filtering just replace the above code with
return result.length > 0 ? true : false

Regex Javascript remove char after 'something' [duplicate]

This question already has answers here:
Remove string after predefined string
(4 answers)
Closed 4 years ago.
I had a sentence like this 'someurl.com/?something=1,2,3' i want to check if the char had something= then remove all character after that.
so like this.
'soome.url/?something=1,2,3,1' => 'soome.url/?'
'soome.url/nothing?nothingtoo?something=1,2,3,1' => 'soome.url/nothing?nothingtoo?'
'soome.url/nothing?something=1,2,3,1' => 'soome.url/nothing?'
how to do that in Javascript?
There are already other pretty good answers with split method.
If you still want to know how to do it with regex
let arr = [`soome.url/?something=1,2,3,1'`
,`soome.url/nothing?nothingtoo?something=1,2,3,1`,
`soome.url/nothing?something=1,2,3,1`]
arr.forEach(e=>{
console.log(e.replace(/\?(?:something=.*)$/g,'?'))
})
Using split and getting the first index will return the string before something=.
const urlOne = 'soome.url/?something=1,2,3,1' // 'soome.url/?'
const urlTwo = 'soome.url/nothing?nothingtoo?something=1,2,3,1' // 'soome.url/nothing?nothingtoo?'
const urlThree = 'soome.url/nothing?something=1,2,3,1' // 'soome.url/nothing?'
function strip(url){
return url.split('something=')[0];
}
console.log(strip(urlOne));
console.log(strip(urlTwo));
console.log(strip(urlThree));
Assuming it's always the last parameter, you could just split the url at something:
const url = 'soome.url/nothing?nothingtoo?something=1,2,3,1';
const newUrl = url.split("something")[0]
console.log(newUrl)
You can also try like following using substr.
let url1 = "soome.url/nothing?nothingtoo?something=1,2,3,1";
let pattern = "something=";
let str2 = url1.substr(0, url1.indexOf(pattern) <= 0 ? str1.length : url1.indexOf(pattern));
console.log(str2);

Match strings using asterisks (wildcards) [duplicate]

This question already has answers here:
Wildcard string comparison in Javascript
(10 answers)
Closed 4 years ago.
I want to test if any string in an array matchs with a particular string. However, the strings in array may contain the asterisks pattern.
var toTest = ["foo_*", "*foo_1", "foo_1*", "bar", "*foo"];
var toMatch = "foo_1";
For this sample, the result will be true because foo_*, *foo_1 and foo_1* will match with foo_1, but bar and *foo won't.
I have tried to use split function with lodash _.some but it seems overcomplicated and I can't make it works consistently.
function isMatching() {
return _.some(toTest , function(a) {
return _.some(a.split("*"), function(part1, idx1) {
return (part1.length && _.some(toMatch.split(part1), function(part2, idx2) {
return (part2.length && idx1 == idx2);
}));
});
});
}
To achieve expected result, use below option of using filter, indexOf and replace
var toTest = ["foo_*", "*foo_1", "foo_1*", "bar", "*_foo"];
var toMatch = "foo_1";
console.log(toTest.filter(v => toMatch.indexOf(v.replace('*', '')) !== -1))

How can i get all clean links via Regex without pattern string [duplicate]

This question already has answers here:
How do you access the matched groups in a JavaScript regular expression?
(23 answers)
Closed 4 years ago.
when i trying this match im getting links like this;
Result:
"video","src":"https:\/\/video-mxp1-1.xx.fbcdn.net\/v\/t42.9040-2\/34384597_178997956146914_227512178675023872_n.mp4"
I want get just cleaned link like this:https:\/\/video-mxp1-1.xx.fbcdn.net\/v\/t42.9040-2\/34384597_178997956146914_227512178675023872_n.mp4
Thanks for your helps;
My codes are below:
var VideoLinks='"type":"video","src":"https:\\\/\\\/video-mxp1-1.xx.fbcdn.net\\\/v\\\/t42.9040-2\\\/34333324_n.mp4?_nc_cat=0&efg=ey1&oe=5B211DB0","width":null"type":"video","src":"https:\\\/\\\/video-mxp1-1.xx.fbcdn.net\\\/v\\\/t42.9040-2\\\/34333324_n.mp4?_nc_cat=0&efg=ey1&oe=5B211DB0","width":null';
My Pattern
pattern =/"video","src":"(.*?)"/g;
var videos=Sitestring.match(pattern);
console.log(videos);
const str = '"video","src":"https:\vid1.mp4"';
const regex = new RegExp('src\":\"(.*)\"', 'i');
console.log(regex.exec(str)[1]);
And about multiple occurences
function getMatch(str, regex) {
const matches = [];
let oneMatch;
do {
oneMatch = regex.exec(str);
if (!oneMatch) {
return matches;
}
matches.push(oneMatch[1]);
} while (oneMatch);
}
const str = '"video","src":"https:vid1.mp4","video","src":"https:vid2.mp4","video","src":"https:vid3.mp4"';
const regex = new RegExp('src\":\"(.*?)\"', 'ig');
console.log(getMatch(str, regex));

How can I create an array including all matches of a regex in JavaScript? [duplicate]

This question already has an answer here:
Put all regex matches in an array?
(1 answer)
Closed 6 years ago.
I have this function which is supposed to put all matches regex returns when executed against a string str into the array res and then return it:
function matchAll(str, regex) {
var res = [];
var m;
while (m = regex.exec(str)) {
res.push(m[0]);
}
return res;
}
It creates an infinite loop with the regex /^\d\d*/i. Why?
Try this regex: \d\s[A-Z0-9]{3,3}
RegexPal (working solution): http://www.regexpal.com/?fam=96072

Categories