Slice a String — Online String Tools

Free online string slicer. Just enter your string and this utility will automatically extract a fragment from it. There are no intrusive ads, popups or nonsense, just a string slicer. Load a string – slice a string. Created for developers by developers from team Browserling.

Check out our main project! Browserling

We created Browserling – get a cloud browser in 5 seconds. Check it out!

string

Import from file

Save as…

Copy to clipboard

Download

Export to Pastebin

sliced string

Can’t convert.

An error has occured.

Chain with…

Remove chain

Save as…

Copy to clipboard

Download

Export to Pastebin

Remove no tools?

This tool cannot be chained.

String slicer options

Slicing Range

Start Point Starting position for the slice (starts at 1).

End Point Ending position for the slice.

Slicing Modes

Multiline Slicing Slice multiple strings on multiple lines at once.

Reverse Symbols Print extracted slice in reverse.

String slicer tool What is a string slicer?

This browser-based program slices strings like a hot knife slices butter. It extracts all characters from a string that are in the range [start, end]. Both range parts are included in the match. For example, if you set the start to 4 and end to 5, and your input string is «goodjob» will turn into a substring «dj». If one of the parameters is missing, then the extracted piece extends to the last (or first) character of the string. For example, for the range [2, ⌴] we get the slice «oodjob» and for the range [⌴, 3] we get the slice «goo». Starting and ending values can also be negative. When working with negative parameters, the last element is the minus first (-1), the second to last is the minus second (-2), and so on. For example, if the range is [-3, -1] then the cropped string will be «job». Combinations of different signs are also acceptable. For example, the interval [3, -4] will turn into «od» and the interval [-3, 6] will turn into «jo». The order of letters in the output doesn’t change, they always go from left to right. If you need to swap characters’ positions, use the «Reverse Symbols» option. You can also use the «Multiline Slicing» option when working with multiple lines.

In this case, individual strings on new lines will be sliced independently. Stringabulous!

String slicer examples Click to use

Slice a Phrase

This example slices a string using a range with positive start and length values. It starts the slice from the eleventh position, which corresponds to the letter «j», and ends the slice at the seventeenth position, which corresponds to the letter «y». As a result, this tool returns a substring with a single word «journey».

Life is a journey, not a race.

journey

Required options

These options will be used automatically if you select this example.

Start Point Starting position for the slice (starts at 1).

End Point Ending position for the slice.

Multiline Slicing Slice multiple strings on multiple lines at once.

Reverse Symbols Print extracted slice in reverse.

Slice Alphabets

In this example, we use a slicing mechanism to extract the last five letters from the Latin, Cyrillic, and Greek alphabets. As each alphabet has a different number of letters, we use the negative values in the range. The position «-1» corresponds to the last character of the alphabet and the position «-5» corresponds to the fifth letter from the end, so we’re slicing backward. We also activate the multi-line slicing mode to get substrings with the last five uppercase and lowercase letters from the alphabets of three different languages.

ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЬЮЯ абвгдежзийклмнопрстуфхцчшщьюя ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩ αβγδεζηθικλμνξοπρστυφχψω

VWXYZ vwxyz ШЩЬЮЯ шщьюя ΥΦΧΨΩ υφχψω

Required options

These options will be used automatically if you select this example.

Start Point Starting position for the slice (starts at 1).

End Point Ending position for the slice.

Multiline Slicing Slice multiple strings on multiple lines at once.

Reverse Symbols Print extracted slice in reverse.

Slice Web Address

This example cleans the input web addresses from the «https» (secure http) protocol, «www» (world wide web) prefixes, and trailing slashes, and extracts just the domain names. As the beginning part of each line is the same («https://www.») and is 12 characters long, the app sets the starting position to 13. As the end part of each line is also the same (it’s a trailing slash), the app sets the ending position to -2, which is the 2nd character from the end. Thus, all characters from the beginning of the string to the 13th position, as well as the last character, are deleted, and only the domain names are returned from each line.

https://www.facebook.com/ https://www.youtube.com/ https://www.google.com/ https://www.catonmat.net/ https://www.wikipedia.org/ https://www.amazon.com/ https://www.netflix.com/

facebook.com youtube.com google.com catonmat.net wikipedia.org amazon.com netflix.com

Required options

These options will be used automatically if you select this example.

Start Point Starting position for the slice (starts at 1).

End Point Ending position for the slice.

Multiline Slicing Slice multiple strings on multiple lines at once.

Reverse Symbols Print extracted slice in reverse.

Timeline of Art Movements

In this example, we crop a timeline of art movements. Each art period is on a new line and we slice all lines at once. We set the crop range from -5 to 13.

This makes the program delete the years and the last word «Art» in each string, leaving only the names of the art periods.

1300 – 1600 Renaissance Art 1600 – 1725 Baroque Art 1720 – 1760 Rococo Art 1760 – 1830 Neoclassical Art 1800 – 1850 Romanticism Art 1840 — 1870 Realism Art 1870 – 1900 Impressionism Art 1880 – 1910 Symbolism Art 1905 – 1925 Expressionism Art 1908 – 1920 Cubism Art 1909 — 1918 Futurism Art 1915 — 1945 Precisionism Art 1959 — 1960 Pop Art

Renaissance Baroque Rococo Neoclassical Romanticism Realism Impressionism Symbolism Expressionism Cubism Futurism Precisionism Pop

Required options

These options will be used automatically if you select this example.

Start Point Starting position for the slice (starts at 1).

End Point Ending position for the slice.

Multiline Slicing Slice multiple strings on multiple lines at once.

Reverse Symbols Print extracted slice in reverse.

Slice and Reverse

This example deletes tens from a list of numbers, leaving only ones, which are then reversed. It specifies only the starting position set to 8 and the utility automatically extracts all letters starting from the eighth position till the end of the string. As the «Reverse Symbols» option is enabled, all letters are printed in reverse order.

twenty-one twenty-two twenty-three twenty-four twenty-five twenty-six twenty-seven twenty-eight twenty-nine

eno owt eerht ruof evif xis neves thgie enin

Required options

These options will be used automatically if you select this example.

Start Point Starting position for the slice (starts at 1).

End Point Ending position for the slice.

Multiline Slicing Slice multiple strings on multiple lines at once.

Reverse Symbols Print extracted slice in reverse.

Slice Email Addresses

In this example, we cut off the «.com» top-level domain suffix from email addresses. To do this, we use only the ending position of the range and leave the starting field empty. In this case, the application extracts all the characters from the first character to the position -5, which is the fifth character from the last.

[email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected]

[email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected]

Required options

These options will be used automatically if you select this example.

Start Point Starting position for the slice (starts at 1).

End Point Ending position for the slice.

Multiline Slicing Slice multiple strings on multiple lines at once.

Reverse Symbols Print extracted slice in reverse.

Pro tips Master online string tools

You can pass input to this tool via

?input

query argument and it will automatically compute output. Here’s how to type it in your browser’s address bar. Click to try!

https://onlinestringtools.com/slice-string?input=Life%20is%20a%20journey%2C%20not%20a%20race.&start=11&end=17&multi-line=false&reverse=false

All string tools

Didn’t find the tool you were looking for? Let us know what tool we are missing and we’ll build it!

URL-encode a String

Quickly URL-escape a string.

URL-decode a String

Quickly URL-unescape a string.

HTML-encode a String

Quickly convert a string to HTML entities.

HTML-decode a String

Quickly convert HTML entities to a string.

Base64-encode a String

Quickly convert a string to base64 encoding.

Base64-decode a String

Quickly decode a base64-encoded string.

Convert a String to a Netstring

Quickly construct a netstring from a regular string.

Convert a Netstring to a String

Quickly decode a netstring and output its contents.

Slash-escape a String

Quickly quote a string with backslashes.

Slash-unescape a String

Quickly un-quote a backslash-quoted string.

Generate a Random String

Quickly generate a random string.

Generate a String from Regex

Quickly generate a string from the given regular expression.

Extract Regex Matches from a String

Quickly extract all regular expression matches from a string.

Test a String with Regex

Quickly check if a string matches a regular expression.

Extract a Substring

Quickly extract a fragment of a string.

Convert a String to an Image

Quickly create an image from a string.

Printf a String

Quickly apply printf (or sprintf) on strings.

Split a String

Quickly split a string into pieces.

Join Strings

Quickly join strings together.

Filter String Lines

Quickly filter lines that match a pattern in a multi-line string.

Repeat a String

Quickly duplicate a string multiple times.

Reverse a String

Quickly reverse a string.

Find and Replace a String

Quickly find and replace parts of a string with a new string.

Truncate a String

Quickly truncate a string to the given length.

Trim a String

Quickly left-trim and right-trim a string.

Left-pad a String

Quickly pad a string on the left.

Right-pad a String

Quickly pad a string on the right.

Right-align a String

Quickly align a string to the right.

Center a String

Quickly center a string.

Sort Strings

Quickly sort a list of strings in alphabetical, alphanumerical or numerical order.

Rotate a String

Quickly rotate a string to the left or to the right.

ROT13 a String

Quickly convert a string to ROT13.

ROT47 a String

Quickly convert a string to ROT47.

Transpose a String

Quickly transpose a string.

Slice a String

Quickly fetch a part of a string.

Add a Prefix to a String

Quickly add a prefix to a string.

Add a Suffix to a String

Quickly add a suffix to a string.

Convert Spaces to Newlines

Quickly convert spaces to newlines in a string.

Convert Newlines to Spaces

Quickly convert newlines to spaces in a string.

Convert Spaces to Tabs

Quickly convert spaces to tabs in a string.

Convert Tabs to Spaces

Quickly convert tabs to spaces in a string.

Remove All Empty Lines

Quickly remove empty lines from a string.

Remove All Whitespace

Quickly remove spaces, tabs, and newlines from a string.

Remove All Punctuation

Quickly remove dots, commas, and other marks from a string.

Find the Length of a String

Quickly calculate a string’s length.

Count Newlines in a String

Quickly calculate the number of newlines in a string.

Convert a String to Bytes

Quickly convert a string to a sequence of bytes.

Convert Bytes to a String

Quickly convert a sequence of bytes to a string.

Convert a String to Binary

Quickly convert a string to a binary string.

Convert Binary to a String

Quickly convert a binary string to a string.

Convert a String to Octal

Quickly convert a string to an octal string.

Convert Octal to a String

Quickly convert an octal string to a string.

Convert a String to Decimal

Quickly convert a string to a decimal string.

Convert Decimal to a String

Quickly convert a decimal string to a string.

Convert a String to Hex

Quickly convert a string to a hexadecimal string.

Convert Hex to a String

Quickly convert a hexadecimal string to a string.

Convert a String to ASCII

Quickly convert a string to ASCII codes.

Convert ASCII to a String

Quickly convert ASCII codes to a string.

Change String Case

Quickly change the case of characters in a string.

Convert a String to Uppercase

Quickly convert a string to uppercase.

Convert a String to Lowercase

Quickly convert a string to lowercase.

Randomize Letter Case in a String

Quickly randomize the case of each letter in a string.

Invert Letter Case in a String

Quickly invert string’s case.

Convert JSON to a String

Quickly extract string data from a JSON data structure.

JSON Stringify a String

Quickly convert a string to a JSON string.

JSON Parse a String

Quickly convert a JSON stringified string to a regular string.

Convert HTML to a String

Quickly extract all string data from a HTML page.

Convert XML to a String

Quickly extract all string data from an XML document.

Convert CSV to a String

Quickly convert a CSV file to evenly aligned columns of space-separated strings.

Convert a String to CSV

Quickly convert strings to a proper CSV file.

Convert BBCode to a String

Quickly extract all string data from a BBCode markup.

Convert a String to Morse Code

Quickly convert a string to Morse code.

Convert Morse Code to a String

Quickly convert Morse code to a string.

Create a Palindrome

Quickly create a palindrome from a string.

Check a Palindrome

Quickly check if a string is a palindrome.

Generate String Unigrams

Quickly generate all monograms of a string.

Generate String Bigrams

Quickly generate all digrams of a string.

Coming soon These string tools are on the way

View and Edit Strings

Quickly edit a string in a browser-based editor.

Replace Multiple Strings

Replace a set of strings with a new set.

Title-case a String

Convert a string to a title with proper titlecase.

Capitalize Words in a String

Convert the first letter of every word in a string to uppercase.

Justify a String

Stretch out a string and align it along the left and right margins.

Format a Multi-line String

Format and align a multi-line string.

Number of Letters in a String

Find how many letters there are in a string.

Number of Words in a String

Find how many words there are in a string.

Number of Lines in a String

Find how many lines there are in a multi-line string.

Number of Paragraphs in a String

Find how many paragraphs there are in a multi-line string.

Sort Words in a String

Sort all words in a string alphabetically.

Sort a Numeric String

Sort a string that contains only numbers.

Reverse Words in a String

Reverse the order of all words in a string.

Reverse Sentences in a String

Reverse the order of all sentences in a string.

String Frequency Analysis

Find most frequent letters, words and phrases in a string.

Create String Mnemonic

Generate a mnemonic for words in a string.

Create an Anagram from a String

Rearrange letters in a string and create a new string.

Number a Multi-line String

Add line numbers to a multi-line string.

Wrap a String

Wrap strings to the given line length.

Chunkify a String

Split a string into chunks of certain length.

Divide a String into Syllables

Find syllables in a string.

Shuffle Words in a String

Shuffle the order of all words in a string.

Extract Emails from a String

Find and extract all email addresses from a string.

Extract URLs from a String

Find and extract all web addresses from a string.

Zigzagify a String

Make a string go in zigzags.

Circlify a String

Make a string go in a circle.

Squarify a String

Make a string go in a square or a rectangle.

Spiralify a String

Make a string go in a spiral.

Blockify a String

Fit a string in an N-by-M block.

Extract Numbers from a String

Find and extract all numbers from a string.

Generate String Statistics

Analyze string’s complexity.

Convert a String to Punycode

Encode a string to punycode.

Convert Punycode to a String

Decode a string from punycode.

QP-encode a String

Convert a string to quoted-printable encoding.

QP-decode a String

Convert quoted-printable encoded data to a string.

Base32-encode a String

Encode a string to base32.

Base32-decode a String

Decode a string from base32.

Base45-encode a String

Encode a string to base45.

Base45-decode a String

Decode a string from base45.

Base58-encode a String

Encode a string to base58.

Base58-decode a String

Decode a string from base58.

Base85-encode a String

Encode a string to Ascii85.

Base85-decode a String

Decode a string from Ascii85.

UTF8-encode a String

Encode a string to UTF8.

UTF8-decode a String

Decode a string from UTF8.

UTF16-encode a String

Encode a string to UTF16.

UTF16-decode a String

Decode a string from UTF16.

UTF32-encode a String

Encode a string to UTF32.

UTF32-decode a String

Decode a string from UTF32.

IDN-encode a String

Encode a string to IDN.

IDN-decode a String

Decode a string from IDN encoding.

Uuencode a String

Convert a string to Unix-to-Unix encoding.

Uudecode a String

Convert Unix-to-Unix data to a string.

Xxencode a String

Convert a string to Xxencoding.

Xxdecode a String

Convert an Xxencoded string to a regular string.

HTML-strip a String

Strip all HTML tags from a string.

Remove Accent Characters

Remove all diacritical signs from a string.

Remove Duplicate Spaces

Normalize string spacing and remove all duplicate spaces.

Diff Two Strings

Visualy compare and find differences between two strings.

String Levenshtein Distance

Calculate Levenshtein distance between two strings.

Rewrite a String

A tiny string rewriting system.

Reduce String Alphabet

Limit the alphabet letters that are used in a string.

Generate a Zalgo String

Convert a string to Unicode mess.

Generate String Typos

Create a list of all possible string typos.

Mirror a String

Generate a mirror copy of a string.

Generate Trigrams

Generate all 3-grams of a string.

Generate all N-grams

Generate all ngrams of a string.

Generate N-skip-M-grams

Generate n-skip-m-grams of a string.

Tokenize a String

Create a list of tokens from a string.

Lemmatize a String

Lemmatize all words in a string.

Stem a String

Do stemming of all words in a string.

Grep a String

Extract fragments that match a regular expression in a string.

Head a String

Split a string into fragments and extract the beginning parts.

Tail a String

Split a string into fragments and extract the ending parts.

Convert a String to an Array

Create an array of characters from a string.

Convert a String to Integers

Split a string into characters and return their integer values.

Replace Letters with Digits

Put digits in place of characters in a string.

Quote a String

Wrap a string in a pair of quotes.

Unquote a String

Remove quotes around a string.

Shift a String

Shift characters in a string to the left or right.

Color a String

Create a colorful string.

Slugify a String

Create a SEO-friendly URL from a string.

Create Mistakes in a String

Substitute random characters in a string and make errors.

Find Mistakes in a String

Run a spell checker and find mistakes in a string.

Mix Two Strings

Interleave two strings character by character.

Generate a Short String

Create a string that doesn’t have too many characters.

Generate a Long String

Create a string that has many characters.

Create a String Cloud

Generate a word cloud from all words in a string.

Subscribe! Never miss an update

Notifications We’ll let you know when we add this tool

Feedback we’d love to hear from you!

Created with love by

51K

@browserling

We’re Browserling — a friendly and fun cross-browser testing company powered by alien technology. At Browserling we love to make developers’ lives easier, so we created this collection of online string tools. Unlike many other tools, we made our tools free, without intrusive ads, and with the simplest possible user interface. Our online string tools are actually powered by our web developer tools that we created over the last couple of years. Check them out!

Secret message

If you love our tools, then we love you, too! Use coupon code STRINGLING to get a discount at Browserling.

Privacy Policy we don’t log data!

All conversions and calculations are done in your browser using JavaScript. We don’t send a single bit about your input data to our servers. There is no server-side processing at all. We use Google Analytics and StatCounter for site usage analytics. Your IP address is saved on our web server, but it’s not associated with any personally identifiable information. We don’t use cookies and don’t store session information in cookies. We use your browser’s local storage to save tools’ input. It stays on your computer.

Terms of Service the legal stuff

By using Online String Tools you agree to our Terms of Service. TLDR: You don’t need an account to use our tools. All tools are free of charge and you can use them as much as you want. You can’t do illegal or shady things with our tools. We may block your access to tools, if we find out you’re doing something bad. We’re not liable for your actions and we offer no warranty. We may revise our terms at any time.

JavaScript: The Definitive Guide, 6th Edition [Book]

Name

String. slice() — извлечь подстроку

Synopsis

    string    14 .14 .    slice    (        start        ,         end        )   

Arguments

start

The string index where the slice is to begin . Если отрицательный, этот аргумент указывает положение, измеряемое от конец строки. То есть −1 указывает последний символ, -2 указывает второй от последнего символа и скоро.

конец

Индекс строки сразу после конца ломтик. Если не указано, фрагмент включает все символы с начало до конца нить. Если этот аргумент отрицательный, он указывает положение измеряется от конца строки.

Возвращает

Новая строка, содержащая все символы строка от включительно начало и до, но не включая конец .

Описание

slice() возвращает строку содержащий фрагмент или подстроку строка . Он не изменяет строка .

Строковые методы slice() , substring() и устаревший substr() указан весь возврат части строки. срез () есть более гибкий, чем substring() потому что он допускает отрицательные значения аргумента. slice() отличается от substr() тем, что указывает подстроку с двумя позициями символов, в то время как substr() использует одну позицию и длину. Также обратите внимание, что String.slice() аналог Array.slice() .

Пример

 var  с   =   "abcdefg"   ; 
  с   .   срез   (   0   ,   4   )   // Возвращает "abcd" 
  с   .   срез   (   2   ,   4   )   // Возвращает "cd" 
  с   .   срез   (   4   )   // Возвращает "efg" 
  с   .   slice   (   3   ,   -   1   )   // Возвращает "def" 
  с   .   срез   (   3   ,   -   2   )   // Возвращает "de" 
  с   .    срез   (   -   3   ,   -   1   )   // Должен вернуть "ef"; возвращает "abcdef" в IE 4  

Ошибки

Отрицательные значения для start не работают в Internet Explorer 4 (но работают в более поздних версиях ...

Get JavaScript: Полное руководство, 6-е издание теперь с обучающей платформой O'Reilly

члена O’Reilly проходят онлайн-обучение в режиме реального времени, а также получают книги, видео и цифровой контент почти от 200 издателей.

Начать бесплатную пробную версию

Основы Javascript · Строка · slice() (метод) | Якуб Корх | Nerd For Tech

Эта статья представляет собой расшифровку моей бесплатной серии YouTube об основах веб-разработки. Если вы предпочитаете смотреть, а не читать, не стесняйтесь посетить мой канал «Dev Newbs».

Привет и добро пожаловать в следующий эпизод, мои коллеги-разработчики! Сегодня будем резать и резать. Метод дня — slice(), не путайте с другим методом slice(). Ха-ха! Как будто кто-то может их спутать, верно?

Метод slice() извлекает части строки и возвращает извлеченные части в новой строке. Первый параметр является обязательным и указывает начальную позицию для извлечения. Второй параметр является необязательным и указывает позицию до окончания извлечения, но не включая ее. Если мы опустим этот параметр, нарезанная подстрока будет идти от начальной позиции до конца строки.

Совет для вас: вы можете использовать отрицательное число для выбора с конца строки. Когда вы указываете отрицательное число для начальной или конечной позиции, счет идет от конца к началу.

Давайте посмотрим, из-за чего весь этот шум в первом примере.

 const str = "Hello Dev Newbs!";// длина строки 
"Length: " + str.length // Длина: 16// получение всей строки
str.slice() // Привет Dev Newbs! // начало среза с позиции 6 (7-й символ)
str.slice(6) // Dev Newbs!// использование отрицательной начальной позиции
// длина + отрицательное значение = позиция
// 16 - 10 = 6 -> начать слайс с
// позиция 6 (7-й символ)
str. slice(-10) // Dev Newbs!// начать слайс с позиции 10 (11-й символ)
// & конец в позиции 14 (15-й символ)
str.slice(10, 15) // Newbs// использование отрицательных позиций
// 16 - 6 = 10 -> начало среза в позиции
// позиция 10 (11-й символ)
// 16 - 1 = 15 -> конец среза по адресу
// позиция 15 (16-й символ)
str.slice(-6, -1) // Newbs

Сначала мы получаем длину строки, с которой будем работать. Он состоит из 16 символов. Эта информация будет важна для отрицательных позиций позже.

Первый вариант — основное использование. Если мы ничего не указываем, используется вся строка. Так что это не очень полезно, так как мы хотим нарезать только часть строки, верно? Тогда исправим.

Второй случай начинается с индекса 6, что означает, что первый символ в нарезанной подстроке является 7-м символом. Конечную позицию мы не указывали, поэтому все остальное брали до конца.

Следующий случай дает тот же результат, только на этот раз мы использовали отрицательное значение для начальной позиции. Вы можете рассчитать, какой индекс вы получите, добавив отрицательное значение к длине вашей строки.

Последние два случая снова идентичны. Они оба получают один и тот же срез, только первый из них использует положительные индексы для начала и конца. Второй использует отрицательные значения. Результат, впрочем, тот же.

Думаю, это все. Я не так много могу вам показать. Что ж, мы можем попробовать какие-нибудь глупые параметры на входе. И мы можем видеть, что мы получаем. Но это все!

 // использование логического значения вместо целого числа -> start = 0, end = 1 
str.slice(false, true) // H// начальный индекс больше конечного -> нечего нарезать
str.slice(6, 0 ) // пустая строка// математическое уравнение в качестве параметров -> start = 6, end = 15
str.slice((4*true+true+15/3), Math.floor(11.4)+29/7) // Newbs// использование глобальных констант в качестве нулевого значения
str.slice(undefined, 5) // Hello

Как и в других методах, нецелые значения могут быть преобразованы в целые значения.