0

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 ?

Lipak
  • 13
  • 5

3 Answers3

1

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

JSFIDDLE

Community
  • 1
  • 1
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400
0

You can use 2 replace statements

str.replace(/\s+/g, "-").replace(/[^a-zA-Z\d]+/g, "")
karina
  • 805
  • 5
  • 10
0

Another way is to select all the text (along with space) which does not have special characters and then replacing spaces with -

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

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

  $('#text').val((str.match(/[a-zA-Z0-9\s]+/gi).join('').trim().replace(/\s+/g, '-')));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" placeholder="Enter page title name" id="text" style="width: 500px;" />
<br />
<br />
<input type="button" value="Click Me" id="button" />
Rajshekar Reddy
  • 18,647
  • 3
  • 40
  • 59
  • thanks :) You are great !! If it is possible then answer my question. How can i do multiple things in javascript when user clicks a button ? – Lipak Apr 24 '16 at 06:47
  • @Lipak what all are your multiple things ?? You can write your script inside the click function – Rajshekar Reddy Apr 24 '16 at 08:06