What’s wrong with this js code?

Asked

Viewed 58 times

2

The first part of the code separates the URL into /

This is the current URL

www.meudominio.com/category/action

var url_atual = decodeURI(window.location.href);
var replace_url = url_atual.replace('http://www.meudominio.com/', '');
var split_url = replace_url.split('/'); 

Now split_url is an array with two values categoria and ação, the function below searches for this category in another object:

var val = split_url[1];
var data = Object.values(livros).filter(function(objecto) { 
    return objecto.categoria.toLowerCase().indexOf(val) > -1 
});

However data is not getting results back if I set manually val = "ação" the search finds all related results, but when it is passed through the URL, no results are found.

Obs: This problem only occurs when there are special characters in the URL if I swap the category for something like adventure or romance search finds results, but when there is a special character or uppercase letter in the URL it returns an empty string.

  • And if you use encodeURI in the parameters ? encodeURI('ação')

3 answers

2


It’s hard to be sure when we can’t simulate here, you return shouldn’t be: return objecto.categoria.toLowerCase().indexOf(val.toLowerCase()) > -1 comparing both in Lower case.

  • Adding toLowerCase() together with val worked perfectly, I was so worried that the problem was in the special characters that I forgot to connect to it.

1

One option is to remove the accent before checking. With SE6 would be:

var str = "Ação"
str = str.normalize('NFD').replace(/[\u0300-\u036f]/g,"");
console.log(str);

  • This doesn’t necessarily solve my problem, but it’s a code I’ll need in the future kk vlw

  • 1

    Yeah, on second thought, hence the string that will test the indexOf will not match. Thanks :P

0

To catch the action value make it easier this way

var url_atual = decodeURI(window.location.href);
var split_url = url_atual.split('/'); 
val = split_url[split_url.length -1]

[val = "action"]

Browser other questions tagged

You are not signed in. Login or sign up in order to post.