Substring a text javascript

JavaScript substring()

Summary: in this tutorial, you’ll learn how to use the JavaScript substring() method to extract a substring from a string.

Introduction to the JavaScript substring() method

The JavaScript String.prototype.substring() returns the part of the string between the start and end indexes:

str.substring(startIndex [, endIndex]) Code language: JavaScript (javascript)

The substring() method accepts two parameters: startIndex and endIndex :

  • The startIndex specifies the index of the first character to include in the returned substring.
  • The endIndex determines the first character to exclude from the returned substring. In other words, the returned substring doesn’t include the character at the endIndex.

If you omit the endIndex , the substring() returns the substring to the end of the string.

If startIndex equals endIndex , the substring() method returns an empty string.

If startIndex is greater than the endIndex , the substring() swaps their roles: the startIndex becomes the endIndex and vice versa.

If either startIndex or endIndex is less than zero or greater than the string.length , the substring() considers it as zero (0) or string.length respectively.

If any parameter is NaN , the substring() treats it as if it were zero (0).

JavaScript substring() examples

Let’s take some examples of using the JavaScript substring() method.

1) Extracting a substring from the beginning of the string example

The following example uses the substring method to extract a substring starting from the beginning of the string:

let str = 'JavaScript Substring'; let substring = str.substring(0,10); console.log(substring);Code language: JavaScript (javascript)
JavaScriptCode language: JavaScript (javascript)

2) Extracting a substring to the end of the string example

The following example uses the substring() to extract a substring from the index 11 to the end of the string:

let str = 'JavaScript Substring'; let substring = str.substring(11); console.log(substring);Code language: JavaScript (javascript)
Substring Code language: JavaScript (javascript)

3) Extracting domain from the email example

The following example uses the substring() with the indexOf() to extract the domain from the email:

let email = 'john.doe@gmail.com'; let domain = email.substring(email.indexOf('@') + 1); console.log(domain); // gmail.comCode language: JavaScript (javascript)
  • First, the indexOf() returns the position of the @ character.
  • Then the substring returns the domain that starts from the index of @ plus 1 to the end of the string.

Summary

  • The JavaScript substring() returns the substring from a string between the start and end indexes.

Источник

substring

Метод substring возвращает подстроку, начиная с позиции indexA до, но не включая indexB .

  • Если indexA = indexB , возвращается пустая строка
  • Если indexB не указан, substring возвращает символы до конца строки
  • Если какой-то из аргументов меньше 0 или является NaN — он считается равным 0
  • Если какой-то из аргументов больше, чем длина строки — он считается равным длине строки

Если indexA > indexB , тогда substring ведет себя, как будто аргументы поменялись местами.

Например, str.substring(1, 0) == str.substring(0, 1) .

var str = "Моя строка" str.substring(0,3) // Моя str.substring(3,0) // Моя str.substring(1,2) // о str.substring(4) // "строка"

целое число от 0 до длины строки-1

Нет ли ошибки? Просто если не включая. То чтобы до конца строки скопировать, надо указать длину строки.

первый символ имеет индекс 0

Чтобы до конца строки скопировать IndexB не вводи.

Кстати таким образом можно читать get запросы))

В описании ошибка, даже Мозилла это подтверждает https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Ob.
Второй indexB не «от 0 до длины строки-1», а просто «от 0 до длины строки». Если я буду вычитать 1 из длины строки, то я никогда не получу последний символ

Последний символ лежит по смещению (длинна строки-1)
потому что первый — по смещению 0.

А можно с конца удалить два символа?

var string = «Some string!»;
string = string.substring(0, string.length — 2);

прошу помочь решить задание
1. Написать функцию, которая ищет первый не повторяющийся символ.

Например: aaggrr55hhjkk результат: j

можно так:
function exist(arr, val) for(var i = 0; i < arr.length; i++)if(arr[i] == val) return true;
>
>
return false;
>
var text = «tpyzatrirallelnoper»;
function firstuniq(text) var arr1 = text.split(»);
var arr = arr1.slice(0)
arr.sort();
var odd = [];
var even = [];
var uniq = [];
for(var i = 0; i < arr.length; i++)!(i % 2) ? odd.push(arr[i]) : even.push(arr[i]);
>
for(var j = 0; j < odd.length; j++)if(!exist(even, odd[j]))
uniq.push(odd[j]);
if(!exist(odd, even[j]))
uniq.push(even[j]);
>
for(var a = 0; a < arr1.length; a++)for(var b = 0; b < unic.length; b++)if(arr1[a] == uniq[b]) return arr1[a];
>
>
>
>
console.log(firstuniq(text));

function firstUniqLiter(str) < try < var result = str.replace(/(.)\1+/g, ''); if(result.length)< return result.substring(0, 1); >return false; >catch(e) < return false; >> console.log(firstUniqLiter('aaggrr55hhhjkk'));

Источник

Читайте также:  Python plot axis name
Оцените статью