подскажите пожалуйста как при помощи регулярки вырезать id
поста, а именно 16011 из ссылки типа: /wp-admin/admin.php?action=duplicate_post_save_as_new_post&post=16011&_wpnonce=bc80ec66ff
Добавить комментарий
|
2 ответа
Вот так вот:
(?<=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}`);
});
}
Я вот так вижу. Но у ответа выше решение красивее и быстрее, я думаю.
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);
-
1
console.log( str.match(/&post=(\d+)/)[1] );
- называется "Группа захвата" )[1]-й
элемент в возвращаемом массиве - тот самый(\d+)
. Можно перестраховаться на случай отсутствия post,console.log( ( str.match(/&post=(\d+)/) || [0,0] )[1] );
3 сен 2020 в 15:27