jQuery Javascript Dynamic Slug Generate - WebJourney

jQuery Javascript Dynamic Slug Generate - WebJourney

To dynamically generate a slug using jQuery, we can utilize a combination of JavaScript and jQuery methods.

 

Here's an example of how we can do this:In this example, we have two input fields: one for the title and another for the generated slug.

 

The jQuery code listens for input events on the title input field and generates the slug dynamically by converting the title to lowercase and replacing any spaces and special symbols like Asterisk (*) ,Hyphe or dash (-) , Ampersat or at(@) , hash (#) , Percent (%) etc with hyphens. The resulting slug is then set as the value of the slug input field.

 

Example Code:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>jQuery Dynamic Slug Generate</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet">
</head>

<body>
    <div class="container mt-5">
        <div class="row">
            <div class="offset-md-3 col-md-6">
                <form>
                    <h4 class="text-success mb-5">jQuery Dynamic Slug Generate</h2>
                    <div class="mb-3">
                        <label for="title" class="form-label">Title</label>
                        <input type="text" class="form-control" id="title">
                    </div>
                    <div class="mb-3">
                        <label for="slug" class="form-label">Slug</label>
                        <input type="text" class="form-control" id="slug">
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.0/jquery.min.js"></script>
    <script>
        //todo:slug generate
        $(document).on('keyup', '#title', function (e) {
            let title = $(this).val();
            let slug = title.replace(/[^a-zA-Z0-9]/g, ' ');
            slug = title.replace(/  +/g, ' ');
            slug = title.replace(/\s/g, '-').toLowerCase().replace(/[^\w-]+/g, '-');
            $('#slug').val(slug);
        });
    </script>
</body>
</html>

 

You can copy this code into an HTML file and open it in a web browser to see it in action. Whenever you type or modify the title, the slug will be automatically generated and updated accordingly.

 

 

Output:

jquery dynamic slug generate

 

 

 

If you like what you are reading, please think about buying us a coffee as a token of appreciation.

Buy Me A Coffee

We appreciate your support and are committed to providing you useful and informative content.

We are thankful for your ongoing support 

Tags

  • Share This: