How can I change some text to lowercase and replac

2020-02-17 10:24发布

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.

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".

<input type="text" name="title" value="This Is A Sample" />
<input type="hidden" name="identifier" value="this-is-a-sample />

5条回答
【Aperson】
2楼-- · 2020-02-17 10:29

To convert to lowercase :

var lowercase = 'This Is A Sample'.toLowerCase();

To Replace empty space:

var Replace= 'This Is A Sample'.replace(/ /g,"-");

take a look at this example

@JSbin

查看更多
Rolldiameter
3楼-- · 2020-02-17 10:35

To switch your text to lowercase, use the JavaScript toLowerCase() method.

<script type="text/javascript">

var str="Hello World!";
document.write(str.toLowerCase());

</script> 

See this Stackoverflow question on how to replace all the spaces with dashes using JavaScript.

查看更多
Anthone
4楼-- · 2020-02-17 10:37

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>
查看更多
Explosion°爆炸
5楼-- · 2020-02-17 10:45

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:

<script type="text/javascript">
$('identifier').value = $('identifier').value.toLowerCase().replace(' ', '-');
</script>
查看更多
闹够了就滚
6楼-- · 2020-02-17 10:49
var lower = $('input#textFieldId').val().toLowerCase(); // to lower case
var hyp = lower.replace(/ /g,"-");                      // spaces to hyphens
$('input#hiddenFieldId').val(hyp);                      // in hidden field

Check

查看更多
登录 后发表回答