JavaScript / jQuery Regex用有效字符替换输入字段 [英] JavaScript/jQuery Regex Replace Input Field with Valid Characters
问题描述
我正在构建一个CMS,用户可以通过文本输入控件自定义页面的SEO URL。例如,假设用户正在创建图库,他们希望通过 http:/来访问他们的页面/www.theirsite.com/my-1st-gallery 。
注意my-1st-gallery部分如何不包含任何非法字符用于URL。由于大多数用户不知道允许和不允许的内容,我想创建一个JavaScript正则表达式过滤器,可以在键入时过滤/转换所有非法字符。
<我知道如何使用jQuery / JavaScript来监听键盘事件,但我不知道如何使用正则表达式来执行以下操作:
- 过滤除az,AZ,0-9, - ,_和空格以外的所有字符。
- 更改任何_和空格到 - ,并让用户知道给定的字符已被转换为 - 。
有人可以提供如何做正则表达式部分的一个很好的例子。再一次,我理解如何倾听关键事件。
感谢您的时间!
好的,有了所有这些好的答案,我想我可以把它拼凑成我的网络应用程序。我希望我可以选择不止一个答案作为我的决赛! :S谢谢大家!
$(#inputElement)。keyup( function(){
var input = $(this),
var text = input.val()。replace(/ [^ a-zA-Z0-9-_ \\\] / g, );
if(/ _ | \s / .test(text)){
text = text.replace(/ _ | \s / g,);
//用于通知用户替换的逻辑
}
input.val(text);
});
I am building a CMS where a user can customize the SEO URL of a page via a text input control. For example, say the user is creating a gallery, and they want their page to be accessed at http://www.theirsite.com/my-1st-gallery.
Notice how the "my-1st-gallery" portion doesn't contain any illegal characters for a URL. Since most users won't know what is allowed and not allowed, I'd like to create a JavaScript regex filter which can filter/convert all illegal characters on key-up.
I know how to use jQuery/JavaScript to listen for key-up events, but I'm not sure how to use a regex to do the following:
- Filter all characters other than a-z, A-Z, 0-9, a "-", a "_", and a space.
- Change any "_" and spaces to a "-", and let the user know that the given character has been converted into "-".
Could someone provide a good example of how to do the regex part. Again, I understand how to listen for key-up events.
Thank you for your time!
Ok, with all of these good answers, I think I can piece this together for my web app. I wish I could select more than one answer as my final! :S Thank you all!
$("#inputElement").keyup(function() {
var input = $(this),
var text = input.val().replace(/[^a-zA-Z0-9-_\s]/g, "");
if(/_|\s/.test(text)) {
text = text.replace(/_|\s/g, "");
// logic to notify user of replacement
}
input.val(text);
});
这篇关于JavaScript / jQuery Regex用有效字符替换输入字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!