0

I have a array on Jquery that have some values .Now i want to replace a character from all the items in the array if it have in the array.

var arrayData = [
       "Safi Landmark Hotel and Suites",
       "Safi Landmark Hotel Suites",
       "Safi Landmark Hotel and Suites"
];

This is my array now i want to replace 'and' from the items with '&' .How can we do this without using loop.

4
  • 2
    Whatever mechanism you use, it will use an iterator inside to go through each item. Is this a matter of syntax? Commented Sep 24, 2014 at 6:26
  • That is our question also, how we can do this without using a loop !!! Commented Sep 24, 2014 at 6:27
  • I think you need to define what you mean by loop? Commented Sep 24, 2014 at 6:29
  • means for loop ..how we can do this with map Commented Sep 24, 2014 at 6:30

3 Answers 3

1

Try this code with map for search and replace:

var testdata = $.map( [ 'a&b', 'abcz&mz', 'test' ], function( abc ) {
        return abc.replace('&',' and ');
    });
      alert(JSON.stringify(testdata));
  });
Sign up to request clarification or add additional context in comments.

2 Comments

Works but the example replace & by and not the other way around like the original post so might be worth updating. It will also replace only the first instance of the searched string.
Also worth mentioning this will loop over the array and that map is slower than a normal for.
1

Here is the fiddle http://jsfiddle.net/xj52nyj0/1/

You can convert the array to string using JSON.jsringify();

and then replace like this.

var arrayData = [
       "Safi Landmark Hotel and Suites",
       "Safi Landmark Hotel Suites",
       "Safi Landmark Hotel and Suites"
];
var x=JSON.stringify(arrayData);
x = x.split('S').join("N");

This doesnt use any looping.

Comments

0

No loop, no jQuery...

var arrayData = [
   "Safi Landmark Hotel and Suites",
   "Safi Landmark Hotel Suites",
   "Safi Landmark Hotel and Suites"
];

console.log(arrayData.join('|*|*|').replace(/and/g,'&').split('|*|*|'));

ps: '| * | * |' is just some unique delimeter..

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.