如何使用 jQuery 将一些文本更改为小写并用连字符替换空格?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3823784/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I change some text to lowercase and replace spaces with hyphens using jQuery?
提问by KarmaKarmaKarma
I have a hidden input field that will take the value of another on keyup and I'm trying to figure out how transform the value in the hidden field to lowercase and replace spaces with hyphens.
我有一个隐藏输入字段,它将在 keyup 上取另一个值,我试图弄清楚如何将隐藏字段中的值转换为小写并用连字符替换空格。
So, if someone types "This Is A Sample" in the title input field, the identifier input field will be set to "this-is-a-sample".
因此,如果有人在标题输入字段中输入“This Is A Sample”,则标识符输入字段将设置为“this-is-a-sample”。
<input type="text" name="title" value="This Is A Sample" />
<input type="hidden" name="identifier" value="this-is-a-sample />
回答by Alpesh
This will replace all spaces with -
这将替换所有空格 -
<script type="text/javascript">
$(document).ready(function(){
var test= $('input[name="title"]').val();
test = test.toLowerCase().replace(/ /g, '-');
$('input[name="identifier"]').val(test);
}):
</script>
回答by Nick
回答by CristiC
You can do it like this:
你可以这样做:
<script type="text/javascript">
var el = document.getElementById('identifier');
var text = el.value;
el.value = text.toLowerCase().replace(' ', '-');
</script>
or if you are using JQuery:
或者如果您使用的是 JQuery:
<script type="text/javascript">
$('identifier').value = $('identifier').value.toLowerCase().replace(' ', '-');
</script>
回答by Naveed
回答by JasCav
To switch your text to lowercase, use the JavaScript toLowerCase() method.
要将文本切换为小写,请使用 JavaScript toLowerCase() 方法。
<script type="text/javascript">
var str="Hello World!";
document.write(str.toLowerCase());
</script>
See this Stackoverflow questionon how to replace all the spaces with dashes using JavaScript.
请参阅有关如何使用 JavaScript 用破折号替换所有空格的Stackoverflow 问题。