مرکزی مواد پر جائیں
eLearner.app
ماڈیول 2 · سبق 2 از 4کورس میں 6/32~10 min
ماڈیول اسباق (2/4)

سٹرنگ کے طریقے

Strings in JS have dozens of methods but in practice you'll use ten of them. They are all functions that don't modify the original string (strings are immutable) but return a new value.

Length, case, search

JS
'JavaScript'.length; // 10
'JavaScript'.toUpperCase(); // 'JAVASCRIPT'
'JavaScript'.toLowerCase(); // 'javascript'

'JavaScript'.includes('Script'); // true
'JavaScript'.startsWith('Java'); // true
'JavaScript'.endsWith('!'); // false

'JavaScript'.indexOf('a'); // 1    (first occurrence, from 0)
'JavaScript'.indexOf('zzz'); // -1   (not found)

length is a property (no parentheses), the others are methods — functions invoked with (…).

Extracting portions with slice

slice(start, end) returns the sub-string between the given positions (end excluded). Negative indices count from the end.

JS
'abcdefgh'.slice(0, 3); // 'abc'
'abcdefgh'.slice(3); // 'defgh'   (omitting end = to the end)
'abcdefgh'.slice(-2); // 'gh'      (last two)

Splitting and rejoining

split(separator) divides a string into an array of pieces. The reverse is join(...) on the array:

JS
'rosso,verde,blu'.split(','); // ['rosso','verde','blu']
['rosso', 'verde', 'blu'].join(' | '); // 'rosso | verde | blu'

Replacing

replace changes the first occurrence, replaceAll changes all of them:

JS
'a-b-c'.replace('-', '_'); // 'a_b-c'
'a-b-c'.replaceAll('-', '_'); // 'a_b_c'

Trim: remove whitespace at the edges

trim() removes spaces (and newlines, tabs) at the start and end. Indispensable when you receive input from a form.

JS
'   ciao  '.trim(); // 'ciao'

Try it

ورزش#js.m2.l2.e1
کوششیں: 0لوڈ ہو رہا ہے…

Given an email `' Mario.Rossi@Example.com '`, normalize it: strip the surrounding spaces and lowercase it. The last expression must evaluate to 'mario.rossi@example.com'.

ایڈیٹر لوڈ ہو رہا ہے…
اشارہ دکھائیں۔

You can chain the methods: first trim(), then toLowerCase().

3 کوششوں کے بعد حل دستیاب ہے۔

Review exercise

ورزش#js.m2.l2.e2
کوششیں: 0لوڈ ہو رہا ہے…

Given the string `'rosso,verde,blu,giallo'`, return as the last expression the NUMBER of colors (i.e. 4).

ایڈیٹر لوڈ ہو رہا ہے…
اشارہ دکھائیں۔

split(',') gives you an array; .length gives you the number of elements.

3 کوششوں کے بعد حل دستیاب ہے۔