1

Hi i am working in java script i have a string

var data = 'http://baab.bh/media/catalog/product/cache/1/image/9df78eab33525d08d6e5fb8d27136e95/t/e/test.jpg';

i want to replace /image/ into 'image/440x600' i am using this function

.replace()

but its not working here is my code

var data ='http://baab.bh/media/catalog/product/cache/1/image/9df78eab33525d08d6e5fb8d27136e95/t/e/test.jpg';
    data.replace('/image/', '/image/440x600/');
    console.log(data);

its showing same not replacing /image/ into 'image/440x600'.

OBAID
  • 1,299
  • 2
  • 21
  • 43

5 Answers5

4

Strings in JavaScript are immutable. Thus the replace function doesn't change the string but returns a new one, you have to use the returned value:

var data = data.replace('/image/', '/image/440x600/');
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
4

Strings in JavaScript are immutable. They cannot be modified.

The replace method returns the modified string, it doesn't modify the original in place.

You need to capture its return value.

var data = 'http://baab.bh/media/catalog/product/cache/1/image/9df78eab33525d08d6e5fb8d27136e95/t/e/test.jpg';
data = data.replace('/image/', '/image/440x600/');
console.log(data);
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
-1
      //Your Actual Data
      var data ='http://baab.bh/media/catalog/product/cache/1/image/9df78eab33525d08d6e5fb8d27136e95/t/e/test.jpg';

        // Changing the reference of the Actual Data and gets a new String
    var ChangedData =data.replace('/image/', '/image/440x600/');

   // To Verify the Output
        console.log(data);

        console.log(ChangedData);
Venkat
  • 2,549
  • 2
  • 28
  • 61
-1

Please check this

    var str = "http://baab.bh/media/catalog/product/cache/1/image/9df78eab33525d08d6e5fb8d27136e95/t/e/test.jpg";

var res = str.replace("image", "image/440x600");

console.log(res);
-2

Using global regular expression

var data = data.replace(/image/g, '/image/440x600/');
MMK
  • 3,673
  • 1
  • 22
  • 30
  • Why? The substring only occurs once in the string in the question. – Quentin Aug 08 '16 at 09:56
  • @Quentin would you like to explain what will be overhead of using this? Its just another way of doing it. – MMK Aug 08 '16 at 10:00
  • What does overhead have to do with it? The OP had a problem. Using a regular expression instead of a string won't solve that problem. Telling them to use a regular expression instead of a string is misleading and doesn't help them. – Quentin Aug 08 '16 at 10:02
  • @Quentin :) i like the term misleading. – MMK Aug 08 '16 at 10:15