I'm trying to check if there is one or more words in a url, how could I proceed? I'm trying to check if a url has in it the category that a product has
I tried like this
const url = "http:/localhost/fast-food-ham/hotdog.html";
const words = "Fast Food";
console.log(
url.toLowerCase().includes(words.toLowerCase())
);
CodePudding user response:
You can use Regular Expressions.
const url = "http:/localhost/fast-food-ham/hotdog.html";
const words = /fast(-|\s)food/i;
if(url.match(words)) {
console.log(true);
} else {
console.log(false);
}
The above code prints true
if the url contains fast food
or fast-food
; false
otherwise.
If you need to print true
if is there a character that is not a space between fast
and food
(eg: fast food
, fast_food
) you can add \S
for the captures in the regular expression:
const words = /fast(-|\s|\S)/i
The last /i
means that the case of the text is ignoring. Since that you don't have to url.toLowerCase()
.
Learn more about regular expressions: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
Hope this helps.
CodePudding user response:
you can split the string to words:
const url = "http:/localhost/fast-food-ham/hotdog.html";
const words = "Fast Food";
words_lst=words.split(" ");
let isexist=false;
for (let word of words_lst)
if(url.toLowerCase().includes(word.toLowerCase())){
isexist=true;
break;
}
console.log(isexist)
have fun :)
CodePudding user response:
you can try this code
let text = "http:/localhost/fast-food-ham/hotdog.html";
let words = "Fast Food";
let a = words.replace(/ /g,"-").toLowerCase();
var regex = new RegExp( a, 'i' );
let result = text.match(regex);