I want to match the last part of the site url with an input value. This string starts with #.
The input value can have accents or not.
This is what I have right now:
$(function () {
var loc = window.location.href.split("#")[0]; // returns the full URL
var href = location.href;
var hrefM = href.match(/#([^\/]*)\/*$/)[1];
var hreflocation = hrefM.replace(/-/g, " ").toProperCase();
if (hreflocation) {
$(".wpcf7-list-item :input[value= '" hreflocation "' ]").parent().addClass("active");
$(".wpcf7-list-item :input[value= '" hreflocation "' ]").attr("checked",true);
}
});
It works fine when there are no accents.
Do you know how to adjust my hrefM so that although this word has no accents it is the same as an input with accents?
For example, this comparison doesn't work right now:
url hreflocation = "#produccio"
<input value="producció">
But this comparison works well:
url hreflocation = "#produccio"
<input value="produccio">
CodePudding user response:
First, I'd like to point out a few things.
- The text after the # in the URL is called the hash, and you can access it with
location.hash. <String>.toProperCaseis not a function.- You cannot match all possible latin diacritics and variations in an attribute selector.
You can instead do:
$(function() {
if (location.hash) {
const hash = location.hash.substring(1).replaceAll('-', ' ');
const matchedInput = $(".wpcf7-list-item input").toArray()
.find(input => input.value.normalize('NFKD').replace(/\p{Diacritic}/gu, '') == hash);
}
});
hashtakes the location hash, removes the#, and converts all-to$(".wpcf7-list-item input").toArray()selects all input elements inside the.wpcf7-list-itemand converts them to an array (to allow you to process them with JavaScript).findlooks for an element in the array whose value, when normalized and stripped of diacritics, is equal tohash
You can then use $(matchedInput) however you want. If you instead want an array of matched inputs, you can replace find with filter.
