Search code examples
javascriptjqueryformat-string

Format String for SEO friendly


I have a string like

Deser't  - & Fest !

how to format this string is seo friendly like Desert-Fest.

In php I use the above function

function cleanString($str, $separator = "-"){
    $q_separator = preg_quote($separator);

    $trans = array(
        '&.+?;'                 => '',
        '[^a-z0-9 _-]'          => '',
        '\s+'                   => $separator,
        '('.$q_separator.')+'   => $separator
    );

    $str = strip_tags($str);

    foreach ($trans as $key => $val){
        $str = preg_replace("#".$key."#i", $val, $str);
    }

    $str = strtolower($str);

    return trim($str, $separator);
}

How to do this in Jquery?

Thanks.


Solution

  • Half of your solution is to HTML-decode the entities in the input. That can be done in JS like this, or jQuery like this.

    From there you can use a regular expression to remove any characters from the resulting string that you don't want, like this:

    function htmlDecode(input) {
      var e = document.createElement('textarea');
      e.innerHTML = input;
      return e.childNodes.length === 0 ? "" : e.childNodes[0].nodeValue;
    }
    
    let input = "Deser't  - & Fest !";
    let output = htmlDecode(input);
    output = output.replace(/[^a-z-]/gi, ''); // remove anything that isn't a-Z or -
    console.log(output);