Jigong Bagong Jigong Bagong - 1 year ago 79
Javascript Question

How to dynamically replace string in javascript

I have this string:

var text1 = "Ferrari Mercedes Ferrari Android iPhone LG iPhone iOS";
//text1 could be anything

I have these arrays:

var cars = ['Toyota', 'BMW', 'Ferrari', 'Mercedes'];
var phones = ['Nokia', 'Samsung', 'LG', 'iPhone'];
// cars values are fixed, but number of array could be increased

I want to replace each word in
with one of the words/values in an array that has a same value, example:

  1. The word Ferrari in
    will match one of
    values, so it will be replaced randomly either by BMW, Toyota, or Mercedes but not Ferrari nor one of the
    values. (let say it was replaced randomly by BMW)

  2. The second Ferrari word will also replaced by BMW

  3. But the Mercedes word in
    must not replaced by BMW and Mercedes

  4. and also the same terms applied for words in
    that categorized in

  5. I expect the result could be something like:

text1 = "BMW Toyota BMW Android Nokia Samsung Nokia iOS";

  1. Android and iOS are not replaced because they are not on any list of array.

What is the effective way to get this?

Answer Source

This is one way of doing it.

  1. Randomly generate two 'offset' numbers between 1 and the length of your arrays (cars/phones)
  2. Create an empty 'mapper' hash to store your mapping of old-new names
  3. Loop through all the index values in your cars array, adding a value to your 'namemapper' with the key = cars[index] and value = cars[index + offset % cars.length], this will ensure that each old name is mapped to a distinct, new name
  4. Do the same thing for phones
  5. Split the string on ' ' to get an array of words (I called this splitText)
  6. Define an empty answer string and both = phones + cars
  7. Use a for loop to access every value of splitText
  8. Within this for-loop, check if each word is in the 'both' array, you can do this by using a second for loop to access every string in the array and check for equality using ===
  9. If it is, append the value corresponding to this key in your mapper to the answer string
  10. Otherwise, append the splitString value to your answer string
  11. Add a space

Here's the code:

var carOffset = Math.ceil(Math.random() * (cars.length-1));
var phoneOffset = Math.ceil(Math.random() * (phones.length -1));
var mapper = {};

for(var i = 0; i < cars.length; i++){
    j = (i + carOffset) % cars.length;
for(var i = 0; i < phones.length; i++){
    j = (i + phoneOffset) % phones.length;

var splitText = text1.split(' ');
var ansString = '';
var both = cars + phones;
for(var i = 0; i < splitText.length; i++){
    var flag = 0;
    for(var j = 0; j< both.length; j++){
            ansString += mapper[splitText[i]];
            flag += 1;
    if(flag === 0){
        ansString += splitText[i];
    ansString += ' ';
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download