我想根据用户在表单上输入的内容创建一个网络友好的图像名称。我想在用户键入时用破折号替换用户输入的字符串中的任何空格。
我的代码只替换了第一个 空格。
如何用破折号替换所有空格?
$('#form_model').keyup(function(event) {
var newText = event.target.value;
newText = newText.replace(" ", "-");
$('#form_image').val(newText+".png");
});
最佳答案
您必须全局替换所有出现的空格。所以,使用这个,
newText = newText.replace(/ /g, "-");
最终代码
$('#form_model').keyup(function(event) {
var newText = event.target.value;
newText = newText.replace(/ /g, "-");
$('#form_image').val(newText+".png");
});
关于javascript - 键入时替换字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46171792/