-5

i'm trying to check if my url contains the word brand. as you can see i put my url into the variable url and now i want to check if that variable contains the word brand and replace it. My only problem is that i can't seem to find the code to check if it contains the word brand.

How do i do this?

<button onclick="myFunction()">navigate</button>
<script>
   function myFunction() 
   {
       var url = document.URL;
       if (window.location.href.match(brand)) 
       {
           alert('yes');
       }
       url = url.replace('.html','.php')
       window.location.href = url;o
    }
</script>
  • 4
    [Here's the first result of a google search for "*how do i check if my string contains certain words javascript*"](http://stackoverflow.com/questions/1789945/how-can-i-check-if-one-string-contains-another-substring?rq=1). I literally just Google'd the title that *you* chose yourself. – h2ooooooo Jan 15 '15 at 14:52
  • 1
    `window.location.href.indexOf('brand') != -1` – David Sherret Jan 15 '15 at 14:52
  • learn to use indexOf method. it is one of the basic – suman Jan 15 '15 at 14:54
  • I feel like an idiot. sorry. Thanks for the reply. – Sven Stoffer Jan 15 '15 at 14:54
  • possible duplicate of [How can I get query string values in JavaScript?](http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript) – Alex Char Jan 15 '15 at 14:55

2 Answers2

0

It should work like that

<button onclick="myFunction()">navigate</button>
<script>
   function myFunction() 
   {
       var url = document.URL;
       if (window.location.href.indexOf('brand') > -1) 
       {
           alert('yes');
       }
       url = url.replace('.html','.php')
       window.location.href = url;
    }
</script>
Francesco
  • 1,383
  • 7
  • 16
0

var url = "http://www.testsbrand.com";

There are two ways can do

  1. RegExp

    (new RegExp('brand')).test(url)

// or

/brand/.test(url)
  1. indexOf:

    url.indexOf('brand') !== -1

Lumi Lu
  • 3,289
  • 1
  • 11
  • 21