В этом руководстве вы изучите методы строки JavaScript с примерами один за другим, как показано ниже.

Пример:-

<html> 
<head> 
<title>Javascript string methods</title> 
</head> 
<body> <p>Below paragraph returns the length of the given string</p> <p id="demo"></p> 
<script> 
let text = "Helloworld"; document.getElementById("demo").innerHTML = text.length; 
</script> 
</body> 
</html>

Вывод:- Below paragraph returns the length of the given string

Также читайте Объект в Javascript с примером

slice():- эта функция извлекает часть заданной строки и возвращает извлеченную строку. Этот строковый метод принимает два параметра: индекс начальной позиции и индекс конечной позиции. Обратите внимание, что индекс начальной позиции начинается с нуля, а индекс конечной позиции не может занимать место в извлеченной строке.

Пример:-

<html> 
<head> 
<title>Javascript string methods</title> 
</head> 
<body> 
<p>Below paragraph extracts a part of the string and returns the extracted string</p> 
<p id="demo1"></p> 
<script> let text = "Helloworld"; document.getElementById("demo1").innerHTML = text.slice(0,5); </script> 
</body> 
</html>

Вывод:- Below paragraph extracts a part of the string and returns the extracted string

substring():- Эта функция аналогична функции slice() и возвращает извлеченную строку из заданной строки.

Пример:-

<html> 
<head> 
<title>Javascript string methods</title> 
</head> 
<body> 
<p>Below paragraph extracts a part of the string and returns the extracted string</p> 
<p id="demo2"></p> 
<script> 
let text = "Helloworld"; 
document.getElementById("demo2").innerHTML = text.substring(0,5); </script> 
</body> 
</html>

Вывод:- Below paragraph extracts a part of the string and returns the extracted string

substr():-Эта функция также похожа на функцию substring(), принимает ровно два параметра и возвращает извлеченную строку из заданной строки.

Пример:-

<html> 
<head> 
<title>Javascript string methods</title> 
</head> 
<body> 
<p>Below paragraph extracts a part of the string and returns the extracted string</p> 
<p id="demo3"></p> 
<script> 
let text = "Helloworld"; 
document.getElementById("demo3").innerHTML = text.substr(0,5); </script> 
</body> 
</html>

Вывод:- Below paragraph extracts a part of the string and returns the extracted string

replace():-Эта функция заменяет некоторую часть строки новой строкой внутри заданной строки. Эта функция принимает ровно два параметра, как указано ниже.

  • Первый параметр определяет заменяемый текст
  • Второй параметр определяет заменяемый текст

Пример: –

<html> 
<head> 
<title>Javascript string methods</title> 
</head> 
<body> 
<p>Below paragraph replaces a part of the string with a new string</p> 
<p id="demo4"></p> 
<script> 
let text = "Helloworld"; 
document.getElementById("demo4").innerHTML = text.replace("world","India"); 
</script> 
</body> 
</html>

Вывод:- Below paragraph replaces a part of the string with a new string

replace() на g:-Эта функция заменяет все совпадающие части заданной строки новой строкой. Эта функция принимает ровно два параметра, как указано ниже.

  • Первый параметр определяет весь соответствующий текст, подлежащий замене.
  • Второй параметр определяет заменяемый текст.

Пример:-

<html> 
<head> 
<title>Javascript string methods</title> 
</head> 
<body> 
<p>Below paragraph replaces all the matching parts of the string with a new string</p> 
<p id="demo5"></p> 
<script> 
let string = "If you want to visit Inida then you should visit the capital of India"; 
document.getElementById("demo5").innerHTML = string.replace(/you/g,"I"); 
</script> 
</body> 
</html>

Вывод:- Below paragraph replaces all the matching parts of the string with a new string

If I want to visit India then I should visit the capital of India

toUpperCase():- Эта функция преобразует все символы заданной строки в верхний регистр. Эта функция не требует никаких параметров.

Пример:-

<html> 
<head> 
<title>Javascript string methods</title> 
</head> 
<body> 
<p>Below paragraph makes the given string in uppercase.</p> 
<p id="demo6"></p> 
<script> 
let string = "If you want to visit Inida then you should visit the capital of India"; 
document.getElementById("demo6").innerHTML = string.toUpperCase(); </script> 
</body> 
</html>

Вывод:- Below paragraph makes the given string in uppercase.

IF YOU WANT TO VISIT INIDA THEN YOU SHOULD VISIT THE CAPITAL OF INDIA

toLowerCase():-Эта функция преобразует все символы заданной строки в нижний регистр. Эта функция также не требует никаких параметров.

Пример:-

<html> 
<head> 
<title>Javascript string methods</title> 
</head> 
<body> 
<p>Below paragraph makes the given string in lowercase.</p> <p id="demo7"></p> 
<script> 
let string = "If you want to visit Inida then you should visit the capital of India"; 
document.getElementById("demo7").innerHTML = string.toLowerCase(); </script> 
</body> 
</html>

Вывод:- Below paragraph makes the given string in lowercase.

if you want to visit inida then you should visit the capital of india

trim():- Эта функция удаляет или устраняет все пробелы, найденные в заданной строке.

Пример:-

<html> 
<head> 
<title>Javascript string methods</title> 
</head> 
<body> 
<p>Below paragraph removes whitespaces from the both side of a string</p> 
<p id="demo9"></p> 
<script> 
let trimstring = "Helloworld"; document.getElementById("demo9").innerHTML = trimstring.trim(); </script> 
</body> 
</html>

Вывод:- Below paragraph removes whitespaces from the both side of a string

charAt():- Эта функция возвращает искомый символ из заданной строки. Предположим, мы хотим найти определенный символ в заданной строке, тогда эта функция поможет нам найти этот символ в заданной строке. Он начинает считать символ с нулевой позиции.

Пример:-

<html> 
<head> 
<title>Javascript string methods</title> 
</head> 
<body> 
<p>Below paragraph will diplay the searched character from a string</p> 
<p id="demo10"></p> 
<script> let text = "Helloworld"; document.getElementById("demo10").innerHTML = text.charAt(5); </script> 
</body> 
</html>

Вывод:- Below paragraph will diplay the searched character from a string

w

charCodeAt():-Эта функция возвращает количество символов Unicode из заданной строки.

Пример:-

<html> 
<head> 
<title>Javascript string methods</title> 
</head> 
<body> 
<p>Below paragraph will diplay the unicode character from a string</p> 
<p id="demo11"></p> 
<script> let text = "Helloworld"; document.getElementById("demo11").innerHTML = text.charCodeAt(5); </script> 
</body> 
</html>

Вывод:- В абзаце ниже будет отображаться символ Unicode из строки 119

padStart():- Эта функция добавляет новую строку в начало заданной строки. Эта функция принимает ровно два параметра, как указано ниже.

  • Первый параметр определяет, сколько раз должна быть добавлена ​​новая строка.
  • Второй параметр определяет новую строку.

Пример:-

<html> 
<head> 
<title>Javascript string methods</title> 
</head> 
<body> 
<p>Below paragraph will pads a string at the start with another string</p> 
<p id="demo12"></p> 
<script> 
let padstring = 3; 
let padnumberstring = padstring.toString(); document.getElementById("demo12").innerHTML = padnumberstring.padStart(5,'y'); 
</script> 
</body> 
</html>

Вывод:- Below paragraph will pads a string at the start with another string

padEnd():- Эта функция добавляет новую строку в конец заданной строки. Эта функция принимает ровно два параметра, как указано ниже.

  • Первый параметр определяет, сколько раз должна быть добавлена ​​новая строка.
  • Второй параметр определяет новую строку.

Примечание.  Если заданная строка является числом, ее следует сначала преобразовать в строку с помощью функции toString() в обоих методах padStart() и padEnd().

Пример:-

<html> 
<head> 
<title>Javascript string methods</title> 
</head> 
<body> 
<p>Below paragraph will pads a string at the end with another string</p> 
<p id="demo13"></p> 
<script> 
let padstring = 3; 
let padnumberstring = padstring.toString(); document.getElementById("demo13").innerHTML = padnumberstring.padEnd(5,'y'); 
</script> 
</body> 
</html>

Вывод:- Below paragraph will pad a string at the end with another string

3yyyy

concat():-Этот метод добавляет новую строку к заданной строке.

Пример:-

<html> 
<head> 
<title>Javascript string methods</title> 
</head> 
<body> 
<p>Below paragraph will join two strings together</p> 
<p id="demo14"></p> 
<script> 
let text1 = "Hello"; 
let text2 = "World"; 
document.getElementById("demo14").innerHTML = text1.concat(" ",text2); 
</script> 
</body> 
</html>

Вывод:- Below paragraph will join two strings together

Заключение: я надеюсь, что это руководство поможет вам понять концепцию строковых методов javascript. Если есть какие-либо сомнения, пожалуйста, оставьте комментарий ниже.

Первоначально опубликовано на https://pbphpsolutions.com 21 сентября 2022 г.