Trying to filter text

Hey guys,

so currently I have the following bit of PHP code which takes an input of text and filters out spaces, unwanted characters etc to help produce friendly URL’s from a title.

function slug($text){
    // replace non letter or digits by -
    $text = preg_replace('~[^\\pL\d]+~u', '-', $text);
    // trim
    $text = trim($text, '-');
    // transliterate
    $text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);
    // lowercase
    $text = strtolower($text);
    // remove unwanted characters
    $text = preg_replace('~[^-\w]+~', '', $text);
    if (empty($text))
        return 'n-a';
    return $text;

I am trying to work out a way to do this using JavaScript for live feedback for the user but I cannot work out the best way to do it.


Are you just trying to make a URL friendly string?

Is this what you’re looking for?

function convertToSlug(Text) {
    return Text
        .replace(/[^\w ]+/g,'')
        .replace(/ +/g,'-');

Taken from: (this answer doesn’t use jQuery, it’s vanilla JS)


indeed that would work ty

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.