1

I have javascript code which is a variable called "x" which value is "Hello World". And also there are two other variables named "old" and "new". All I want is to when I give a random value to variable "Old" and new value to variable "new". Then I need the program to find and replace the similar character in the sentence with the new value.

Ex : old = "l" , new = "y", new sentence would need to become "Heyyo World" which replace the 'l' letter with 'y'.

Below is my sample code.

<script type="text/javascript">
function fndReplace()
{
   var x = "Hello world";
   var old = "l";
   var neww = "y";
   var i;

   var length = x.length;
   for(i=0;i<length-1;i++)
   {
      if(old[i] == neww)
      {
          old = old[i] + neww
      }
   }
   
   document.write(old);
}

    fndReplace();
   
</javascript>

2

3 Answers 3

1

Javascript is a functional langauage, so the for structure is discouraged if it's not necessary. In fact, there is a prebuilt function part of the String library which can accomplish this goal: String.prototype.replace().

Nina's answer is good if you want to use for, but here's another way to do it:

var xArr = x.split('');
xArr.forEach(function(e, index) {
  if(e === old) {
    xArr[index] = neww;
  }
});
x = xArr.join('');

Sign up to request clarification or add additional context in comments.

Comments

0

Strings are in Javascript immutable. You need a new assignment to the variable with the changed content.

You could use String#replace to replace directly a pattern.

function fndReplace(string, o, n) {
    return string.replace(new RegExp(o, 'g'), n);
}

console.log(fndReplace('Hello world', 'l', 'y'));

If you like to mutate single letters with index, you could split the string and change the array. After changing, you can join the array to a new string.

function fndReplace(string, o, n) {
    var letters = string.split(''),
        i,
        length = letters.length;

    for (i = 0; i < length; i++) {
        if (letters[i] === o) {
            letters[i] = n;
        }
    }
    return letters.join('');
}

console.log(fndReplace('Hello world', 'l', 'y'));

ES6 with spread syntax ... and Array#map.

function fndReplace(string, o, n) {
    return [...string].map(c => c === o ? n : c).join('');
}

console.log(fndReplace('Hello world', 'l', 'y'));

Comments

0

If you don't want to use String.replace() you can make a pretty small function with Array.map() and Array.join(). Might be better to String.split() instead of calling map on the string, but it shaves off 1 character if you're playing golf.

let findReplace = (x, y, z) => [].map.call(x, c => c === y ? z : c).join('');
console.log(findReplace('Hello world', 'l', 'y'));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.