Reputation: 471
Hi i need to strip all spaces and newlines from a string in javascript... This is what i use and it doesn't work...
<script language="JavaScript" type="text/javascript">
<!--
var isShift=null;
var isNN = (navigator.appName.indexOf("Netscape")!=-1);
var OP = (navigator.appName.indexOf("Opera")!=-1);
if(OP)isNN=true;
var key;
function shift(event){
key = (isNN) ? event.which : event.keyCode;
if (key==16)isShift=1;
}
function process(event){
key = (isNN) ? event.which : event.keyCode;
if(document.layers&&event.modifiers==4){
isShift=1;
}
if (key==13&&isShift!=1){
var chatmsg = $("#chatmsg");
var cmessage = chatmsg.val();
cmessage = cmessage.replace(/\s/g, '');
if(cmessage=="")
{
document.myForm.chatmsg.value = "";
return false;
}
else
{
sendMsg();
}
}
if (key!=16)isShift=null;
}
//-->
function sendMsg(){
var chatmsg = $("#chatmsg");
$.post("sendchat.php",{ chatmsg: chatmsg.val()} ,
function(data)
{
$("#msgtousr").html(data).show();
$("#msgtousr").html(data).fadeOut(2000);
document.myForm.chatmsg.value = "";
});
}
</script>
<form name='myForm' method='POST' style='margin:0px'>
<textarea name='chatmsg' onkeypress='return process(event)' onkeydown='shift(event)' style='width:278px;height:70px;border:2px solid white;background-color:turquoise;color:blue' id='chatmsg'></textarea>
</form>
This is my chat if it has an error checking if the user typed something in in the javascript i suspect the replace function to misbehave
Upvotes: 3
Views: 7469
Reputation: 19495
Try...
cmessage = cmessage.replace(/\s/g, '');
\s
in this case stands for "all white space" which includes spaces and newline characters.
Upvotes: 2
Reputation: 224942
You want to strip all spaces and newlines? Only one regex is necessary:
cmessage = cmessage.replace(/\s/g, '');
Upvotes: 12