نريد أن نتيح هذا المشروع المفتوح المصدر إلى كل الناس حول العالم. من فضلك ساعدنا على ترجمة محتوى هذه السلسله للغة التى تعرفها.
الرجوع الي الدرس

أدخل بعد المقدمة

لدينا سلسلة مع مستند HTML.

اكتب تعبيرًا عاديًا يُدرج <h1> مرحبًا </ h1> مباشرة بعد علامة <body>. قد يكون للسمات سمات.

على سبيل المثال:

let regexp = /your regular expression/; let str = ` <html> <body style="height: 200px"> ... </body> </html> `; str = str.replace(regexp, `<h1>Hello</h1>`);

بعد هذا من المفترض أن تصبح قيمة str:

<html> <body style="height: 200px"><h1>Hello</h1> ... </body> </html>

In order to insert after the <body> tag, we must first find it. We can use the regular expression pattern <body.*?> for that.

في هذه المهمة ، لا نحتاج إلى تعديل علامة <body>. نحتاج فقط لإضافة النص بعده.

إليك كيفية القيام بذلك:

let str = '...<body style="...">...'; str = str.replace(/<body.*?>/, '$&<h1>Hello</h1>'); alert(str); // ...<body style="..."><h1>Hello</h1>...

In the replacement string $& means the match itself, that is, the part of the source text that corresponds to <body.*?>. It gets replaced by itself plus <h1>Hello</h1>.

البديل هو استخدام lookbehind:

let str = '...<body style="...">...'; str = str.replace(/(?<=<body.*?>)/, `<h1>Hello</h1>`); alert(str); // ...<body style="..."><h1>Hello</h1>...

كما ترون ، هناك فقط جزء وراء النظر في هذا التعبير العادي.

It works like this:

  • At every position in the text.
  • Check if it’s preceeded by <body.*?>.
  • If it’s so then we have the match.

The tag <body.*?> won’t be returned. The result of this regexp is literally an empty string, but it matches only at positions preceeded by <body.*?>.

So it replaces the “empty line”, preceeded by <body.*?>, with <h1>Hello</h1>. That’s the insertion after <body>.

P.S. Regexp flags, such as s and i can also be useful: /<body.*?>/si. The s flag makes the dot . match a newline character, and i flag makes <body> also match <BODY> case-insensitively.