Forum Moderators: open

Message Too Old, No Replies

replace function

cant get this to work

         

will1480

5:09 am on Jun 28, 2004 (gmt 0)

10+ Year Member



This is code for phone number validation. I want to remove all non digit characters and check that the length is 10.

phone=document.ship_info.phone.value;
phone.replace(/\D*/g,"");

if(phone.length!=10){
alert("You entered an invalid phone number.");
}

The replace doesnt do anything. Cant get even the most simple example to work like:
text="java";
text.replace(/java/, "not java");

Rambo Tribble

5:30 am on Jun 28, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



This works on any JavaScript interpreter I have (IE, Moz, Opera).

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Untitled</title>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
<style type="text/css">
html,body{height:100%}
</style>
<script type="text/javascript">
function strRep(){
var text="not java";
var txt2=text.replace(/not java/,"JavaScript");
alert(text);
alert(txt2);
}
</script>
</head>
<body onclick="strRep();">

</body>
</html>

Bernard Marx

8:40 am on Jun 28, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



The replace doesnt do anything. Cant get even the most simple example to work like:
text="java";
text.replace(/java/, "not java");

I make this mystake, myself quite often.

The correct form, would be:

text="java"; 
text = text.replace(/java/, "not java");

The important thing being that strings are 'immutable'.
If you want to change a string, you need a new one, which is what string methods produce. They don't change the original.

will1480

12:22 pm on Jun 28, 2004 (gmt 0)

10+ Year Member



ah ha. Thank you very much. That was a frustrating mistake. Yeah, it has a return value of the new string huh.