[英]Skipping the special characters from users input of a text string and adding Hyphen after every word in Javascript
Html: 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) 用户输入:: ::“这是Ram的笔吗?”(不带双引号)
When user click the button, the input should be.. 当用户单击按钮时,输入应为
EXPECTED :: " Is-this-Rams-pen " (Without double quote) 预期的::“ Is-this-Rams-pen”(不带双引号)
Main aim is to adding Hyphen(-) in between every word and skipping the other special characters. 主要目的是在每个单词之间添加连字符(-),并跳过其他特殊字符。
Is it possible in Javascript ? Javascript是否可能?
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(/[^a-z0-9\\s]/gi, '')
将字符串过滤为仅字母数字字符。 replace(/[_\\s]/g, '-')
replaces all underscores and spaces with hyphens. replace(/[_\\s]/g, '-')
用连字符替换所有下划线和空格。
Source of Regex: RegEx for Javascript to allow only alphanumeric 正则表达式的来源: Java的RegEx仅允许字母数字
您可以使用2条替换语句
str.replace(/\s+/g, "-").replace(/[^a-zA-Z\d]+/g, "")
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" />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.