Lipak Lipak - 7 months ago 11
Javascript Question

Skipping the special characters from users input of a text string and adding Hyphen after every word in Javascript

Html:

<input type="text" placeholder="Enter page title name" id="text" style="width: 500px;" />
<br />
<br />
<input type="button" value="Click Me" id="button" />


USER INPUT :: " Is this Ram's pen ? " (Without double quote)

When user click the button, the input should be..

EXPECTED :: " Is-this-Rams-pen " (Without double quote)

Main aim is to adding Hyphen(-) in between every word and skipping the other special characters.

Is it possible in Javascript ?

Answer

Use this piece of code.

$('#button').on('click', function() {

    var str = $('#text').val();

  $('#text').val((str.replace(/[^a-z0-9\s]/gi, '').trim().replace(/[_\s]/g, '-')));
})

replace(/[^a-z0-9\s]/gi, '') filters the string to just alphanumeric characters. replace(/[_\s]/g, '-') replaces all underscores and spaces with hyphens.

Source of Regex: RegEx for Javascript to allow only alphanumeric