tpai
7/11/2017 - 2:51 AM

URL String Replacement// source http://jsbin.com/gabugay

URL String Replacement// source http://jsbin.com/gabugay

'use strict';

function resize(str, size) {
  if (typeof size === 'undefined') return str;
  return str.replace(/(https?):\/\/picture-original.cdn.com\/([^.]*).(jpe?g|png|gif)/ig, function (match, protocol, key, ext) {
    return protocol + '://picture-thumb.cdn.com/' + key + '-' + size + '.' + ext;
  });
}

console.assert(resize('https://picture-original.cdn.com/page-localhost-2017710.jpg', 300) === 'https://picture-thumb.cdn.com/page-localhost-2017710-300.jpg', { msg: 'test1 failed' });
console.assert(resize('https://picture-original.cdn.com/page-localhost-2017710-1499674105998.jpg', 300) === 'https://picture-thumb.cdn.com/page-localhost-2017710-1499674105998-300.jpg', { msg: 'test2 failed' });
console.assert(resize('https://picture-thumb.cdn.com/page-localhost-2017710.jpg', 300) === 'https://picture-thumb.cdn.com/page-localhost-2017710.jpg', { msg: 'test3 failed' });
console.assert(resize('https://picture-thumb.cdn.com/page-localhost-2017710-1499674105998-600.jpg', 300) === 'https://picture-thumb.cdn.com/page-localhost-2017710-1499674105998-600.jpg', { msg: 'test4 failed' });