Home > Mobile >  Compare and match last part of URL with and accented/unaccented input value
Compare and match last part of URL with and accented/unaccented input value

Time:01-28

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.

  1. The text after the # in the URL is called the hash, and you can access it with location.hash.
  2. <String>.toProperCase is not a function.
  3. 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);
  }
});
  • hash takes the location hash, removes the #, and converts all - to
  • $(".wpcf7-list-item input").toArray() selects all input elements inside the .wpcf7-list-item and converts them to an array (to allow you to process them with JavaScript)
  • .find looks for an element in the array whose value, when normalized and stripped of diacritics, is equal to hash

You can then use $(matchedInput) however you want. If you instead want an array of matched inputs, you can replace find with filter.

  •  Tags:  
  • Related