jQuery: Replace multiple regex matches with string?
I am trying to use this block of code to replace ALL "12开发者_运维技巧3"'s in a long string with a different number.
var new_id = new Date().getTime();
$('#food').after(
"<div id='123' name='123'> etc etc".replace('123', new_id)
);
But it's only replacing the first 123 with the new_id. Is there a way to replace all of them?
You need to make it a regex instead of a plain vanilla string and add the /g
flag.
"<div id='123' name='123'> etc etc".replace(/123/g, new_id)
replace(/123/g, new_id)
This is regex literal syntax with a global (g
) flag.
精彩评论