سلسلة فرعية JavaScript String ()
أمثلة
استخراج سلسلة فرعية من النص:
let text = "Hello world!";
let result = text.substr(1, 4);"
ابدأ من الموضع 2:
let result = text.substr(2);
المزيد من الأمثلة أدناه.
التعريف والاستخدام
تستخرج الطريقة substr()
جزءًا من سلسلة.
تبدأ substr()
الطريقة في موضع محدد ، وتعيد عددًا محددًا من الأحرف.
الطريقة substr()
لا تغير السلسلة الأصلية.
لاستخراج الأحرف من نهاية السلسلة ، استخدم موضع بداية سالب.
بناء الجملة
string.substr(start, length)
المعلمات
Parameter | Description |
start | Required. The start position. First character is at index 0. If start is greater than the length, substr() returns "". If start is negative, substr() counts from the end of the string. |
length | Optional. The number of characters to extract. If omitted, it extracts the rest of the string |
قيمة الإرجاع
نوع | وصف |
سلسلة | سلسلة تحتوي على الجزء المستخرج. إذا كان الطول 0 أو سالب ، يتم إرجاع سلسلة فارغة. |
مزيد من الأمثلة
فقط الأول:
let result = text.substr(0, 1);
فقط الأخير:
let result = text.substr(text.length-1, 1);
آخر 6:
let result = text.substr(-5, 5);
دعم المتصفح
substr()
هي إحدى ميزات ECMAScript1 (ES1).
ES1 (JavaScript 1997) مدعوم بالكامل في جميع المتصفحات:
Chrome | IE | Edge | Firefox | Safari | Opera |
Yes | Yes | Yes | Yes | Yes | Yes |