Jump to content

Problem with string.replace()

- - - - -

  • Please log in to reply
3 replies to this topic

#1
thatsme

thatsme

    Programmer

  • Members
  • PipPipPipPip
  • 176 posts
Hi. This code should find if the value of field begins with "370" and if so, replace this begining with "8". So the output in the last line should be 84 if the input was 3704. However the bolded line does not change anything. Could anyone help to find out why?

    var numberBegining = /^(370)?/.exec(field.value);
    alert(numberBegining[0]);
    if (numberBegining != null && numberBegining[0] != "") {
        numberBegining[0] = "8";
        [B](field.value).replace("370", numberBegining[0]);[/B]
        alert("new value: " + field.value);
    }


#2
fayyazlodhi

fayyazlodhi

    Programming Expert

  • Members
  • PipPipPipPipPipPip
  • 403 posts
Which language is it? I thought C# at first but that does not accept regular expressions at least the way they are written in first line.

I just verified that in VS 2010.

#3
thatsme

thatsme

    Programmer

  • Members
  • PipPipPipPip
  • 176 posts
It's javascript

#4
fayyazlodhi

fayyazlodhi

    Programming Expert

  • Members
  • PipPipPipPipPipPip
  • 403 posts
Ok i am not a java script guy. Still i might be able to help out.

 numberBegining[0] != "") {

        numberBegining[0] = "8";


First i believe numberBeginning is an array, so numberBeginning[0] is one element of array which canot be compared to a string i.e. "".

A string generally means more than one char, so either you do numberBeginning == "" OR numberBeginning[0] == '' // Compare with single char.

Secondly, unless javascript is fundamentally different from any other programming language, "370" is a constant, not a variable. So replacing it with another value makes little sense.

Why do you need to do it?

Can't you just create a string variable, place 370 in it first and then replace it with the 8? That is the logical way of writing any program.

If it is to change latter it should be a variable right?

Hope that helps.




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users