I am horrible at Regex, what i want is to check if a string has the word http twice, for example : http://stackoverflow.com/questions/askhttp://stackoverflow.com/questions/ask, using the awesome feature of regex in javascript.
thanks.
I am horrible at Regex, what i want is to check if a string has the word http twice, for example : http://stackoverflow.com/questions/askhttp://stackoverflow.com/questions/ask, using the awesome feature of regex in javascript.
thanks.
/http.*http/
Is the simplest expression that does this. That is http anywhere in the string followed by zero or more characters followed by http.
Although not exactly answering the question. Why not use indexOf() with offset, like so:
var offset = myString.indexOf(needle);
if(myString.indexOf(needle, offset)){
// This means string occours more than one time
}
indexOf is quicker than regex. Also, it is a bit less exposed to special chars ruining the code.
Another way, which can be extended to more than n times or exactly n times easily:
(inputString.match(/http/g) || []).length >= n
If you want to extend it to any literal string, you can use RegExp constructor with the input string after regex-escaping:
(inputString.match(new RegExp(escapeRegex(needle), 'g')) || []).length >= n
escapeRegex function replicated here for convenience:
function escapeRegex(input) {
return input.replace(/[[\](){}?*+^$\\.|]/g, '\\$&');
}
No need for a regex, you could use a little function like this that utilises String.indexOf and performs a word count.
EDIT: perhaps "word count" is a bad description and better would be "pattern matches"
Javascript
var testString = "http://stackoverflow.com/questions/askhttp://stackoverflow.com/questions/ask",
testWord = "http";
function wc(string, word) {
var length = typeof string === "string" && typeof word === "string" && word.length,
loop = length,
index = 0,
count = 0;
while (loop) {
index = string.indexOf(word, index);
if (index !== -1) {
count += 1;
index += length;
} else {
loop = false;
}
}
return count;
}
console.log(wc(testString, testWord) > 1);
On jsfiddle
// this code check if http exists twice
"qsdhttp://lldldlhttp:".match(/http.*http/);