JavaScript String Methods

10 min read

String methods help you to work with strings.

Үсэгт аргууд нь үгнүүдтэй ажиллахад тусалдаг.


String Methods and Properties #

Үсгэн арга ба шинж чанарууд #

Primitive values, like “John Doe”, cannot have properties or methods (because they are not objects).

“Жон До” шиг анхдагч утгууд нь шинж чанар, аргуудтай байж чадахгүй (учир нь тэдгээр нь объект биш).

But with JavaScript, methods and properties are also available to primitive values, because JavaScript treats primitive values as objects when executing methods and properties.

Гэхдээ JavaScript-ийн хувьд арга, шинж чанарууд нь командыг ашиглах боломжтой байдаг, учир нь JavaScript нь арга, шинж чанаруудыг хэрэгжүүлэхдээ анхдагч утгуудыг объект гэж үздэг.


String Length #

Үсэгний урт #

The length property returns the length of a string:

Length шинж чанар нь үсгийн уртыг буцаана:

Example Жишээ #

var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; var sln = txt.length;

Finding a String in a String #

Өгүүлбэрээс үг олох #

 

The indexOf() method returns the index of (the position of) the first occurrence of a specified text in a string:

indexOf() арга нь өгүүлбэрт заасан текстийн first тохиолдлын индексийг (байрлал) буцаана.

Example Жишээ #

var str = "Please locate where 'locate' occurs!"; var pos = str.indexOf("locate");

JavaScript counts positions from zero.

JavaScript нь байрлалыг тэгээс тоолно.

0 is the first position in a string, 1 is the second, 2 is the third …

0 нь үгийн эхний байрлал, 1 нь хоёр дахь, 2 нь гурав дахь …

The lastIndexOf() method returns the index of the last occurrence of a specified text in a string:

lastIndexOf() арга нь заасан текстийн сүүлчийн тохиолдлын индексийн үгийг буцаана.

Example Жишээ #

var str = "Please locate where 'locate' occurs!"; var pos = str.lastIndexOf("locate");

Both indexOf(), and lastIndexOf() return -1 if the text is not found.

Текст олдохгүй бол indexOf() ба lastIndexOf() хоёулаа -1 буцаана.

Example Жишээ #

var str = "Please locate where 'locate' occurs!"; var pos = str.lastIndexOf("John");

Both methods accept a second parameter as the starting position for the search:

Хоёр арга нь хоёрдахь параметрийг хайлтын эхлэх байрлал болгон хүлээн авдаг.

Example Жишээ #

var str = "Please locate where 'locate' occurs!"; var pos = str.indexOf("locate", 15);

The lastIndexOf() methods searches backwards (from the end to the beginning), meaning: if the second parameter is 15, the search starts at position 15, and searches to the beginning of the string.

lastIndexOf()аргууд нь араас нь (төгсгөлөөс эхлэл хүртэл) хайдаг бөгөөд энэ нь: хэрэв хоёрдахь параметр нь 15 бол хайлт 15-р байрлалаас эхэлж мөрийн эхэнд хайх болно.

Example Жишээ #

var str = "Please locate where 'locate' occurs!"; var pos = str.lastIndexOf("locate", 15);

Searching for a String in a String #

Өгүүлбэрээс үг хайж байна #

The search() method searches a string for a specified value and returns the position of the match:

Search () арга нь үгийг тодорхойлсон утгыг хайж, тохирох байрлалыг буцаана.

Example Жишээ #

var str = "Please locate where 'locate' occurs!"; var pos = str.search("locate");

Did You Notice? #

Та анзаарсан уу? #

The two methods, indexOf() and search(), are equal?

indexOf() ба search ()гэсэн хоёр арга тэнцүү үү?

They accept the same arguments (parameters), and return the same value?

Тэд ижил аргумент (параметр) -ийг хүлээн зөвшөөрч, ижил утгыг буцааж өгдөг үү?

The two methods are NOT equal. These are the differences:

Хоёр арга тэнцүү биш байна. Эдгээр ялгаа нь:

  • The search() method cannot take a second start position argument.

    search() арга нь хоёрдахь эхлэлийн байрлалын аргумент авч чадахгүй.

  • The indexOf() method cannot take powerful search values (regular expressions).

    indexOf() арга нь хүчирхэг хайлтын утга (тогтмол илэрхийлэл) авч чадахгүй.

You will learn more about regular expressions in a later chapter.

Тогтмол хэллэгүүдийн талаар та дараачийн бүлгээс олж мэдэх болно.


 
 
 
 
 
 
 

Extracting String Parts #

Үгийн хэсгүүдийг задлах #

There are 3 methods for extracting a part of a string:

Үгийн хэсгийг задлах 3 арга байдаг:

  • slice(startend)
  • substring(startend)
  • substr(startlength)

The slice() Method #

slice() арга #

slice() extracts a part of a string and returns the extracted part in a new string.

slice () нь үгийн хэсгийг задалж гаргаж авсан хэсгийг шинэ үгэнд буцаана.

The method takes 2 parameters: the start position, and the end position (end not included).

Арга нь 2 параметрийг авдаг: эхлэх байршил, төгсгөлийн байрлал (төгсгөл ороогүй).

This example slices out a portion of a string from position 7 to position 12 (13-1):

Энэ жишээ нь үгийн хэсгийг 7-р байрлалаас 12-р байрлал хүртэл (13-1) зүснэ.

Example Жишээ #

var str = "Apple, Banana, Kiwi"; var res = str.slice(7, 13);

The result of res will be:

Үр дүнгийн үр дүн нь:

Banana

Remember: JavaScript counts positions from zero. First position is 0.

Санаж байгаарай: JavaScript нь байрлалыг тэгээс тоолно. Эхний байрлал 0 байна.

If a parameter is negative, the position is counted from the end of the string.

Хэрэв параметр сөрөг бол байрлалыг үгийн төгсгөлөөс тоолно.

This example slices out a portion of a string from position -12 to position -6:

Энэ жишээ нь үгийн хэсгийг байрлалаас -12 байрлалаас -6 байрлал руу зүснэ.

Example Жишээ #

var str = "Apple, Banana, Kiwi"; var res = str.slice(-12, -6);

The result of res will be:

Үр дүнгийн үр дүн нь:

Banana

If you omit the second parameter, the method will slice out the rest of the string:

Хэрэв та хоёрдахь параметрийг орхигдвол арга нь үгийн үлдсэн хэсгийг зүсэх болно.

Example Жишээ #

var res = str.slice(7);

or, counting from the end:

эсвэл төгсгөлөөс нь тоолох:

Example Жишээ #

var res = str.slice(-12);

Negative positions do not work in Internet Explorer 8 and earlier.

Internet Explorer 8 ба түүнээс өмнөх хувилбаруудад сөрөг байр суурь ажиллахгүй.


The substring() Method #

substring() арга #

substring() is similar to slice().

substring() нь slice() -тэй төстэй юм.

The difference is that substring() cannot accept negative indexes.

Үүний ялгаа нь substring() сөрөг индексийг хүлээн авах боломжгүй юм.

Example Жишээ #

var str = "Apple, Banana, Kiwi"; var res = str.substring(7, 13);

The result of res will be:

Үр дүнгийн үр дүн нь:

Banana

If you omit the second parameter, substring() will slice out the rest of the string.

Хэрэв та хоёрдахь параметрийг орхигдуулсан бол substring() үг нь үлдсэн мөрийг хэрчинэ.


The substr() Method #

substr() арга #

substr() is similar to slice().

substr() нь slice() -тэй төстэй юм.

The difference is that the second parameter specifies the length of the extracted part.

Үүний ялгаа нь хоёрдахь параметр нь олборлосон хэсгийн уртыг зааж өгдөгт оршино.

Example Жишээ #

var str = "Apple, Banana, Kiwi"; var res = str.substr(7, 6);

The result of res will be:

Үр дүнгийн үр дүн нь:

Banana

If you omit the second parameter, substr() will slice out the rest of the string.

Хэрэв та хоёрдахь параметрийг орхигдуулсан бол substr()нь үгийн үлдсэн хэсгийг зүснэ.

Example Жишээ #

var str = "Apple, Banana, Kiwi"; var res = str.substr(7);

The result of res will be:

Үр дүнгийн үр дүн нь:

Banana, Kiwi

If the first parameter is negative, the position counts from the end of the string.

Хэрэв эхний параметр сөрөг байвал байрлал нь үгийн төгсгөлөөс тоолно.

Example Жишээ #

var str = "Apple, Banana, Kiwi"; var res = str.substr(-4);

The result of res will be:

Үр дүнгийн үр дүн нь:

Kiwi

Replacing String Content #

String агуулгыг солих #

The replace() method replaces a specified value with another value in a string:

replace() арга нь заасан утгыг үг доторх өөр утгатай орлуулна.

Example Жишээ #

str = "Please visit Microsoft!"; var n = str.replace("Microsoft", "Apprentice");

The replace() method does not change the string it is called on. It returns a new string.

replace() арга нь дуудсан үгийг өөрчлөхгүй. Энэ нь шинэ үгийг буцаана.

By default, the replace() method replaces only the first match:

Анхдагч байдлаар, replace() арга нь зөвхөн эхний хэсгийг орлуулдаг:

Example Жишээ #

str = "Please visit Microsoft and Microsoft!"; var n = str.replace("Microsoft", "Apprentice");

By default, the replace() method is case sensitive. Writing MICROSOFT (with upper-case) will not work:

Анхдагч байдлаар replace() арга нь жижиг үсгийн мэдрэмжтэй байдаг. MICROSOFT бичих (том үсгээр) ажиллахгүй:

Example Жишээ #

str = "Please visit Microsoft!"; var n = str.replace("MICROSOFT", "Apprentice");

To replace case insensitive, use a regular expression with an /i flag (insensitive):

Жижиг үсгийн мэдрэмжийг орлуулахын тулд ердийн илэрхийлэлийг /i тугтай (мэдрэмжгүй) ашиглана уу:

Example Жишээ #

str = "Please visit Microsoft!"; var n = str.replace(/MICROSOFT/i, "Apprentice");

Note that regular expressions are written without quotes.

Ердийн хэллэгийг ишлэлгүйгээр бичдэг болохыг анхаарна уу.

To replace all matches, use a regular expression with a /g flag (global match):

Бүх тохирлыг солихын тулд ердийн илэрхийлэлийг /g тугтай ашиглана уу (глобал тэмцээн):

Example Жишээ #

str = "Please visit Microsoft and Microsoft!"; var n = str.replace(/Microsoft/g, "Apprentice");

You will learn a lot more about regular expressions in the chapter JavaScript Regular Expressions.

Жирийн хэллэгүүдийн талаар та JavaScript-ийн байнгын илэрхийлэл бүлгээс илүү их зүйлийг сурах болно.


Converting to Upper and Lower Case #

Дээд, жижиг үсгээр хөрвүүлэх #

A string is converted to upper case with toUpperCase():

Мөрийг toUpperCase() -ээр том үсгээр хөрвүүлдэг:

Example Жишээ #

var text1 = "Hello World!"; // String var text2 = text1.toUpperCase(); // text2 is text1 converted to upper

A string is converted to lower case with toLowerCase():

Үгийг toLowerCase () үсгээр жижиг үсгээр хөрвүүлдэг:

Example Жишээ #

var text1 = "Hello World!"; // String var text2 = text1.toLowerCase(); // text2 is text1 converted to lower

The concat() Method #

concat() арга #

concat() joins two or more strings:

concat () нь хоёр ба түүнээс дээш үгнүүдтэй нийлдэг:

Example Жишээ #

var text1 = "Hello"; var text2 = "World"; var text3 = text1.concat(" ", text2);

The concat() method can be used instead of the plus operator. These two lines do the same:

Нэмэх операторын оронд concat()аргыг ашиглаж болно. Эдгээр хоёр үг нь ижил зүйлийг хийдэг.

Example Жишээ #

var text = "Hello" + " " + "World!"; var text = "Hello".concat(" ", "World!");

All string methods return a new string. They don’t modify the original string.

Бүх үгийн аргууд нь шинэ үгийг буцаана. Тэд анхны үгийг өөрчлөхгүй.

Formally said: Strings are immutable: Strings cannot be changed, only replaced.

Албан ёсоор хэлэхдээ: Үгүүд өөрчлөгддөггүй: Үгнүүдийг өөрчлөх боломжгүй, зөвхөн солигддог.


String.trim() #

The trim() method removes whitespace from both sides of a string:

trim() арга нь үгний хоосон зайг арилгана.

Example Жишээ #

var str = " Hello World! "; alert(str.trim());

The trim() method is not supported in Internet Explorer 8 or lower.

trim() аргыг Internet Explorer 8 эсвэл түүнээс доош хувилбаруудад дэмждэггүй.

If you need to support IE 8, you can use replace() with a regular expression instead:

Хэрэв танд IE 8-ийг дэмжих шаардлагатай бол оронд ньreplace() ердийн илэрхийлэлтэй ашиглаж болно:

Example Жишээ #

var str = " Hello World! "; alert(str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ''));

You can also use the replace solution above to add a trim function to the JavaScript String.prototype:

Та дээрх орлуулах шийдлийг ашиглан JavaScript String.prototype дээр засах функцийг нэмж оруулах боломжтой.

Example Жишээ #

if (!String.prototype.trim) { String.prototype.trim = function () { return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ''); }; } var str = " Hello World! "; alert(str.trim());

JavaScript String Padding #

ECMAScript 2017 added two String methods: padStart and padEnd to support padding at the beginning and at the end of a string.

Example #

let str = "5"; str = str.padStart(4,0); // result is 0005

Example #

let str = "5"; str = str.padEnd(4,0); // result is 5000

String Padding is not supported in Internet Explorer.

Firefox and Safari were the first browsers with support for JavaScript string padding:

Chrome 57 Edge 15 Firefox 48 Safari 10 Opera 44
Mar 2017 Apr 2017 Aug 2016 Sep 2016 Mar 2017

Extracting String Characters #

There are 3 methods for extracting string characters:

  • charAt(position)
  • charCodeAt(position)
  • Property access [ ]

The charAt() Method #

The charAt() method returns the character at a specified index (position) in a string:

Example #

var str = "HELLO WORLD"; str.charAt(0); // returns H

The charCodeAt() Method #

The charCodeAt() method returns the unicode of the character at a specified index in a string:

The method returns a UTF-16 code (an integer between 0 and 65535).

Example #

var str = "HELLO WORLD"; str.charCodeAt(0); // returns 72

Property Access #

ECMAScript 5 (2009) allows property access [ ] on strings:

Example #

var str = "HELLO WORLD"; str[0]; // returns H

Property access might be a little unpredictable:

  • It does not work in Internet Explorer 7 or earlier
  • It makes strings look like arrays (but they are not)
  • If no character is found, [ ] returns undefined, while charAt() returns an empty string.
  • It is read only. str[0] = “A” gives no error (but does not work!)

Example #

var str = "HELLO WORLD"; str[0] = "A"; // Gives no error, but does not work str[0]; // returns H

If you want to work with a string as an array, you can convert it to an array.


Converting a String to an Array #

A string can be converted to an array with the split() method:

Example #

var txt = "a,b,c,d,e"; // String txt.split(","); // Split on commas txt.split(" "); // Split on spaces txt.split("|"); // Split on pipe

If the separator is omitted, the returned array will contain the whole string in index [0].

Хэрэв тусгаарлагч орхигдсон бол буцаасан багц нь [0] индекс дэх бүхэл үгийг агуулна.

If the separator is “”, the returned array will be an array of single characters:

Хэрэв тусгаарлагч нь “” бол буцаагдсан багц нь дан тэмдэгтүүдийн багц болно:

Example Жишээ #

var txt = "Hello"; // String txt.split(""); // Split in characters

Complete String Reference #

Бүрэн үгийн лавлагаа #

For a complete reference, go to our Complete JavaScript String Reference.

Бүрэн лавлагаа авахын тулд манай Бүрэн JavaScript String лавлагаа руу орно уу.

The reference contains descriptions and examples of all string properties and methods.

Лавлагаа нь бүх үгийн шинж чанар, аргуудын тодорхойлолт, жишээг агуулдаг.

Powered by BetterDocs

Leave a Reply