regex для строки js
подскажите пожалуйста как при помощи регулярки вырезать id поста, а именно 16011 из ссылки типа: /wp-admin/admin.php?action=duplicate_post_save_as_new_post&post=16011&_wpnonce=bc80ec66ff
Ответы (2 шт):
Автор решения: dIm0n
→ Ссылка
Вот так вот:
(?<=post=)\d+
http://skolerom.loc/wp-admin/admin.php?action=duplicate_post_save_as_new_post&post=16011&_wpnonce=bc80ec66ff
/wp-admin/admin.php?action=duplicate_post_save_as_new_post&post=16011&_wpnonce=bc80ec66ff
Сгенерированный код:
const regex = /(?<=post=)\d+/gm;
const str = `http://skolerom.loc/wp-admin/admin.php?action=duplicate_post_save_as_new_post&post=16011&_wpnonce=bc80ec66ff
/wp-admin/admin.php?action=duplicate_post_save_as_new_post&post=16011&_wpnonce=bc80ec66ff`;
let m;
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
console.log(`Found match, group ${groupIndex}: ${match}`);
});
}
Автор решения: Alex Sazonov
→ Ссылка
Я вот так вижу. Но у ответа выше решение красивее и быстрее, я думаю.
const regexp = /&post=[\d]+/;
const str = 'http://skolerom.loc/wp-admin/admin.php?action=duplicate_post_save_as_new_post&post=16011&_wpnonce=bc80ec66ff';
let resultId = str.match(regexp)[0].match(/\d+/)[0];
console.log(resultId);