如何同时将空格替换为下划线(当我在输入字段中输入文本时)?

Roh*_*hit 10 regex jquery

你能告诉我如何同时将空格替换为下划线(当我在输入栏中输入文字时)?如果我有字符串我就这样使用.

replace(/ /g,"_");
Run Code Online (Sandbox Code Playgroud)

但我正在寻找当用户在输入字段上输入文本然后它自动用下划线替换空格.我使用的键盘事件它只是第一次触发.

$("#test").keyup(function() {
  var textValue = $(this).val();
    if(textValue==' '){
        alert("hh");
    }
});
Run Code Online (Sandbox Code Playgroud)

Tus*_*har 14

DEMO

$("#test").keyup(function () {
    var textValue = $(this).val();
    textValue =textValue.replace(/ /g,"_");
    $(this).val(textValue);
});
Run Code Online (Sandbox Code Playgroud)

更新

DEMO

$("#test").keyup(function () {
    this.value = this.value.replace(/ /g, "_");
});
Run Code Online (Sandbox Code Playgroud)