3

So basically I want to do something different for a site if the url contains a specific string, lets say: 'foo'

So this is what I have:

var url = document.URL;
var substring = 'foo';
if(the substring is in the url){
//do something
}
else{
//do something
};

So what would go in the if() to make this possible?

gherkins
  • 14,603
  • 6
  • 44
  • 70
Ryan Saxe
  • 17,123
  • 23
  • 80
  • 128

3 Answers3

3

You can use the indexOf method

// Function is used to determine whether a string contains another string
function contains(search, find) {
    ///<summary>Sees if a string contains another string</summary>
    ///<param type="string" name="search">The string to search in</param>
    ///<param type="string" name="find">The string to find</param>
    ///<returns type="bool">A boolean value indicating whether the search string contained the find string</returns>
    return search.indexOf(find) !== -1;
}

Here's some sample usage:

var url = document.URL;
var substring = 'foo';
if (contains(url.toLowerCase(), substring.toLowerCase()) { 
// Contains string
}

The contains function is case sentitive, however; as demonstrated in my example, you can make it incasesensitive by calling the StringPrototype.toLowerCase Method

Rasmus Søborg
  • 3,597
  • 4
  • 29
  • 46
1

You may use indexOf for example :

if (url.indexOf(substring)>=0) {
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
0

This is a forward-looking answer, and won't work in current implementations.

ECMAScript 6 is currently defining a String.prototype.contains method. This will allow you to do:

if (url.contains(substring)) {

Again, this is a future addition. Currently ECMAScript 6 (Harmony) is being drafted, and this could technically be removed, though it doesn't seem likely.

Current draft:

15.5.4.24 String.prototype.contains (searchString, position = 0 )

The contains method takes two arguments, searchString and position, and performs the following steps:

  1. Let O be CheckObjectCoercible(this value).
  2. Let S be ToString(O).
  3. ReturnIfAbrupt(S).
  4. Let searchStr be ToString(searchString).
  5. ReturnIfAbrupt(searchStr).
  6. Let pos be ToInteger(position). (If position is undefined, this step produces the value 0).
  7. ReturnIfAbrupt(pos).
  8. Let len be the number of elements in S.
  9. Let start be min(max(pos, 0), len).
  10. Let searchLen be the number of characters in searchStr.
  11. If there exists any integer k not smaller than start such that k + searchLen is not greater than len, and for all nonnegative integers j less than searchLen, the character at position k+j of S is the same as the character at position j of searchStr, return true; but if there is no such integer k, return false.
  • If you're having trouble understanding this answer, please ask instead of down-voting, though I don't know how it could possibly be more clear or well documented than what I've described. –  Jun 28 '13 at 20:11