Javascript search in url

How to check if the URL contains a given string?

I have a long URL like this, preview.tbwabox.co.nz/_v005/index.html#buying-a-car and I want to check if the string has «buying-a-car but the script» isn’t working?

@Vennsoh You’re not able to find «buying-a-car» because you need to look in window.location.hash not window.location.href . Simply swap those values out in OP’s function.

@Elshan Because, strictly speaking, .href.indexOf(«franky») can return a value of 0 if .href begins with «franky». Of course, in this case, it never does as .href always begins with the protocol, typically «http:» or «file:». Despite this, you should ALWAYS use >-1, >=0 or, my preference, !==-1 when comparing with the result of indexOf() .

I have an array of value and want to see if the Url has any of the value and give me the index of the array that matches the condition. How do I do that? Thanks.

if (window.location.href.indexOf("franky") != -1) 

would do it. Alternatively, you could use a regexp:

if (/franky/.test(window.location.href)) 

const url = new URL(window.location.href); const path = url.pathname; if (/^\/test($|\/|-)/.test(path)) < //do >This is the way

if(window.location.href.indexOf("franky") != -1)

Also notice the addition of href for the string otherwise you would do:

if(window.location.toString().indexOf("franky") != -1)

window.location isn’t a String, but it has a toString() method. So you can do it like this:

(''+window.location).includes("franky") 
window.location.toString().includes("franky") 

Location objects have a toString method returning the current URL. You can also assign a string to window.location. This means that you can work with window.location as if it were a string in most cases. Sometimes, for example when you need to call a String method on it, you have to explicitly call toString.

In Firefox 48, String.prototype.contains() has been removed. Use String.prototype.includes() only. See Here

@starsplusplus There isn’t any difference. window.location.href is an alias of window.location developer.mozilla.org/en-US/docs/Web/API/Window.location

@VinothNarayan You can simply add another condition to the if statement. To make sure it has both, you can use the AND operator, which is && in Javascript: if( window.location.href.indexOf(«cart») > -1 && window.location.href.indexOf(«box») > -1 ) To check if it has one or the other value, use the OR operator, which is two pipe characters || if( window.location.href.indexOf(«cart») > -1 || window.location.href.indexOf(«box») > -1 )

var matches = !!location.href.match(/franky/); //a boolean value now 

Or in a simple statement you could use:

if (location.href.match(/franky/))  

I use this to test whether the website is running locally or on a server:

location.href.match(/(192.168|localhost).*:1337/) 

This checks whether the href contains either 192.168 or localhost AND is followed by :1337 .

As you can see, using regex has its advantages over the other solutions when the condition gets a bit trickier.

Alternatively, it feels a bit more concise to me to use if(/franky/.test(location.href)) < /* regex matched */ >if I'm not doing anything with the matches.

document.URL should get you the URL and

if(document.URL.indexOf("searchtext") != -1) < //found >else < //nope >

Try this, it's shorter and works exactly as window.location.href :

if (document.URL.indexOf("franky") > -1)

also if you want to check the previous URL:

if (document.referrer.indexOf("franky") > -1)

@sixstarpro I didn't do the downvote, but, oh I don't know, maybe obviously because you gave the same answer as this one posted 18 months previously! Also, the extra info about document.referrer is completely irrelevant to the question.

It will be a good practice if you convert your string to lower or uppercase as indexof() method is case sensitive.

This will be if your search isn't case sensitive you can simply use indexOf() method without converting the orignal string to lowercase or uppercase:

var string= location.href; var convertedString= string.toLowerCase(); if(convertedString.indexOf('franky') != -1) < alert("url has franky"); >else

I like this approach, instead.

top.location.pathname.includes('franky') 

You can also try search (for regular expressions)

Use Window.location.href to take the url in javascript. it's a property that will tell you the current URL location of the browser. Setting the property to something different will redirect the page.

if (window.location.href.indexOf('franky') > -1)

How to check if a url is default page and string iam checking is not visible . like for example sample.com/homepage.aspx is my page and iam looking for string 'homepage'. if((loc.toString().toUpperCase().indexOf('homepage') > -1))<> works fine but when Iam on sample.com(which still points to homepage.aspx) above code will not work.How to check for this scenario as well?please help!

I like to create a boolean and then use that in a logical if .

//kick unvalidated users to the login page var onLoginPage = (window.location.href.indexOf("login") > -1); if (!onLoginPage) < console.log('redirected to login page'); window.location = "/login"; >else

a window location is an object that contains multiple methods and props some of them is strings related to URL so you can search for the targeted string safely:

const href = location.href; // "https://stackoverflow.com/questions/4597050/how-to-check-if-the-url-contains-a-given-string" // another option const pathname = location.pathname; // "/questions/4597050/how-to-check-if-the-url-contains-a-given-string" // search for string safely pathname.includes("questions"); // true href.includes("questions"); // true 
 var url = window.location.href; console.log(url); console.log(~url.indexOf("#product-consulation")); if (~url.indexOf("#product-consulation")) < console.log('YES'); // $('html, body').animate(< // scrollTop: $('#header').offset().top - 80 // >, 1000); > else

I didn't know ~ , so I looked it up: " ~ is a trick to turn indexOf() 's found return value into truthy (while making not-found as falsy). People otherwise use it for its side effect of truncating numbers. " - stackoverflow.com/a/12299678/3917091

Regular Expressions will be more optimal for a lot of people because of word boundaries \b or similar devices. Word boundaries occur when any of 0-9 , a-z , A-Z , _ are on that side of the next match, or when an alphanumeric character connects to line or string end or beginning.

if (location.href.match(/(?:\b|_)franky(?:\b|_))) 

If you use if(window.location.href.indexOf("sam") , you'll get matches for flotsam and same , among other words. tom would match tomato and tomorrow, without regex.

Making it case-sensitive is as simple as removing the i .

Further, adding other filters is as easy as

if (location.href.match(/(?:\b|_)(?:franky|bob|billy|john|steve)(?:\b|_)/i)) 

Let's talk about (?:\b|_) . RegEx typically defines _ as a word character so it doesn't cause a word boundary. We use this (?:\b|_) to deal with this. To see if it either finds \b or _ on either side of the string.

Other languages may need to use something like

if (location.href.match(/([^\wxxx]|^)(?:franky|bob|billy|john|steve)([^\wxxx]|$)/i)) //where xxx is a character representation (range or literal) of your language's alphanumeric characters. 

All of this is easier than saying

var x = location.href // just used to shorten the code x.indexOf("-sam-") || x.indexOf("-sam.") || x.indexOf(" sam,") || x.indexOf("/sam"). // and other comparisons to see if the url ends with it // more for other filters like frank and billy 

Other languages' flavors of Regular Expressions support \p but javascript does not, which would make the task of detecting foreign characters much easier. Something like [^\p](filters|in|any|alphabet)[^\p]

Источник

Как разобрать URL в JavaScript?

Представляю Вашему вниманию перевод заметки «How to Parse URL in JavaScript: hostname, pathname, query, hash» автора Dmitri Pavlutin.

Унифицированный указатель ресурса или, сокращенно, URL — это ссылка на веб-ресурс (веб-страницу, изображение, файл). URL определяет местонахождения ресурса и способ его получения — протокол (http, ftp, mailto).

Например, вот URL данной статьи:

https://dmitripavlutin.com/parse-url-javascript 

Часто возникает необходимость получить определенные элементы URL. Это может быть название хоста (hostname, dmitripavlutin.com ) или путь (pathname, /parse-url-javascript ).

Удобным способом получить отдельные компоненты URL является конструктор URL() .

В этой статье мы поговорим о структуре и основных компонентах URL.

1. Структура URL

Изображение лучше тысячи слов. На представленном изображении Вы можете видеть основные компоненты URL:

2. Конструктор URL()

Конструктор URL() — это функция, позволяющая разбирать (парсить) компоненты URL:

const url = new URL(relativeOrAbsolute [, absoluteBase]) 

Аргумент relativeOrAbsolute может быть абсолютным или относительным URL. Если первый аргумент — относительная ссылка, то второй аргумент, absoluteBase , является обязательным и представляет собой абсолютный URL — основу для первого аргумента.

Например, инициализируем URL() с абсолютным URL:

const url = new URL('http://example.com/path/index.html') url.href // 'http://example.com/path/index.html' 

Теперь скомбинируем относительный и абсолютный URL:

const url = new URL('/path/index.html', 'http://example.com') url.href // 'http://example.com/path/index.html' 

Свойство href экземпляра URL() возвращает переданную URL-строку.

После создания экземпляра URL() , Вы можете получить доступ к компонентам URL. Для справки, вот интерфейс экземпляра URL() :

Здесь тип USVString означает, что JavaScript должен возвращать строку.

3. Строка запроса (query string)

Свойство url.search позволяет получить строку запроса URL, начинающуюся с префикса ? :

const url = new URL( 'http://example.com/path/index.html?message=hello&who=world' ) url.search // '?message=hello&who=world' 

Если строка запроса отсутствует, url.search возвращает пустую строку (''):

const url1 = new URL('http://example.com/path/index.html') const url2 = new URL('http://example.com/path/index.html?') url1.search // '' url2.search // '' 
3.1. Разбор (парсинг) строки запроса

Вместо получения исходной строки запроса, мы можем получать ее параметры.

Легкий способ это сделать предоставляет свойство url.searchParams . Значением данного свойства является экземпляр интерфейса URLSeachParams.

Объект URLSearchParams предоставляет множество методов для работы с параметрами строки запроса ( get(param), has(param) и т.д.).

Давайте рассмотрим пример:

const url = new Url( 'http://example.com/path/index.html?message=hello&who=world' ) url.searchParams.get('message') // 'hello' url.searchParams.get('missing') // null 

url.searchParams.get('message') возвращает значение параметра message строки запроса.

Доступ к несуществующему параметру url.searchParams.get('missing') возвращает null .

4. Название хоста (hostname)

Значением свойства url.hostname является название хоста URL:

const url = new URL('http://example.com/path/index.html') url.hostname // 'example.com' 

5. Путь (pathname)

Свойство url.pathname содержит путь URL:

const url = new URL('http://example.com/path/index.html?param=value') url.pathname // '/path/index.html' 

Если URL не имеет пути, url.pathname возвращает символ / :

const url = new URL('http://example.com/'); url.pathname; // '/' 

6. Хеш (hash)

Наконец, хеш может быть получен через свойство url.hash :

const url = new URL('http://example.com/path/index.html#bottom') url.hash // '#bottom' 

Если хеш отсутствует, url.hash возвращает пустую строку (''):

const url = new URL('http://example.com/path/index.html') url.hash // '' 

7. Проверка (валидация) URL

При вызове конструктора new URL() не только создается экземпляр, но также осуществляется проверка переданного URL. Если URL не является валидным, выбрасывается TypeError .

Например, http ://example.com не валидный URL, поскольку после http имеется пробел.

Попробуем использовать этот URL:

Поскольку 'http ://example.com' неправильный URL, как и ожидалось, new URL('http ://example.com') выбрасывает TypeError .

8. Работа с URL

Такие свойства, как search, hostname, pathname, hash доступны для записи.

Например, давайте изменим название хоста существующего URL с red.com на blue.io :

const url = new URL('http://red.com/path/index.html') url.href // 'http://red.com/path/index.html' url.hostname = 'blue.io' url.href // 'http://blue.io/path/index.html' 

Свойства origin, searchParams доступны только для чтения.

9. Заключение

Конструктор URL() является очень удобным способом разбора (парсинга) и проверки (валидации) URL в JavaScript.

new URL(relativeOrAbsolute, [, absoluteBase] в качестве первого параметра принимает абсолютный или относительный URL. Если первый параметр является относительным URL, вторым параметром должен быть абсолютный URL — основа для первого аргумента.

После создания экземпляра URL() , Вы можете получить доступ к основным компонентам URL:

  • url.search — исходная строка запроса
  • url.searchParams — экземпляр URLSearchParams для получения параметров строки запроса
  • url.hostname — название хоста
  • url.pathname — путь
  • url.hash — значение хеша

Источник

Читайте также:  Настройка бэкграунда в css
Оцените статью