1

我有以下代码,正确实现了 jQuery(它已经过测试):

var notrightfake = $("#ansbox").val();
var notright = notrightfake.replace(" ", "");

并且$("#ansbox")是一个input type="text"盒子。但是假设我输入了He llo t his is m e,程序不应该显示Hellothisisme,而不是根本不工作吗?

jsFiddle 示例:http: //jsfiddle.net/WUvu5/

谢谢您的支持,

卢卡斯·陈

4

4 回答 4

6

replace函数仅替换第一次出现的子字符串。

您必须使用正则表达式来替换所有匹配项:

var notright = notrightfake.replace(/ /g, "");
于 2012-04-24T06:38:00.327 回答
1

您必须进行实际替换,您只需将其分配给代码中的变量。

var notrightfake = $("#ansbox").val();
$("#ansbox").val(notrightfake.replace(" ", ""));

编辑:您必须在活动中使用它,即。keyup

$('input').keyup(function(){
    var newValue = this.value.replace(/\s/, '');
    $(this).val(newValue);
});

演示:http: //jsfiddle.net/elclanrs/3YWxh/

于 2012-04-24T06:38:31.637 回答
0

试试这个
notrightfake.replace(/ /gi, "");

于 2012-04-24T06:38:34.153 回答
0

试试下面的代码:

var notrightfake = $("#ansbox").val();
var notright = notrightfake.replace(/\s+/g, "");
alert(notright);

或者您可以使用一些修剪功能:

function trim(str) {
    return str.replace(/^\s+|\s+$/g,"");
};
function ltrim(str) {
    return str.replace(/^\s+/,"");
};
function rtrim(str) {
    return str.replace(/\s+$/,"");
};
于 2012-04-24T06:51:25.537 回答