AngeloC AngeloC - 6 days ago 5
Javascript Question

How to replace sub string after the portion of match in javascript?

I'd like to change everything after '=img' into something else, following code does not work:

var j = '/test/123=img?xyze'
j.replace(/=img\.*/, '');


Any idea how? Thanks,

A.C.

Answer
var j = '/test/123=img?xyze'
j=j.replace(/(=img)(.*)/, '$1_somethingElse');
console.log(j); //  "/test/123=img_somethingElse"

$1 is =img and the rest would be in $2 if you needed it.

Further reading: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Switching_words_in_a_string