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>
  • Possible duplicate of [How to replace all occurrences of a string in JavaScript?](https://stackoverflow.com/questions/1144783/how-to-replace-all-occurrences-of-a-string-in-javascript) – emed Sep 01 '17 at 18:18
  • 1
    why not replace the `'l'` in `'world'`? – Nina Scholz Sep 01 '17 at 18:40

3 Answers3

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('');
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'));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
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'));
Will
  • 3,201
  • 1
  • 19
  • 17