js字符串slice_JavaScript子字符串示例-JS中的Slice,Substr和Substring方法

js字符串slice

In daily programming, we often need to work with strings. Fortunately, there are many built-in methods in JavaScript that help us while working with arrays, strings and other data types. We can use these methods for various operations like searching, replacing, concatenating strings, and so on.

在日常編程中,我們經常需要使用字符串。 幸運的是,JavaScript中有許多內置方法可以在處理數組,字符串和其他數據類型時為我們提供幫助。 我們可以將這些方法用于各種操作,例如搜索,替換,串聯字符串等。

Getting a substring from a string is one of the most common operations in JavaScript. In this article, you’re going to learn how to get a substring by using 3 different built-in methods. But first, let me explain briefly what a substring is.

從字符串中獲取子字符串是JavaScript中最常見的操作之一。 在本文中,您將學習如何使用3種不同的內置方法來獲取子字符串。 但首先,讓我簡要解釋一下什么是子字符串。

什么是子串? (What is a Substring?)

A substring is a subset of another string:

子字符串是另一個字符串的子集:

"I am learning JavaScript and it is cool!"  -->  Original String"I am learning JavaScript"  -->  Substring"JavaScript is cool!"  -->  Another Substring

Like in the example above, in some cases we need to get one or more substrings from a complete sentence or a paragraph. Now let’s see how to do that in JavaScript in 3 different ways.

像上面的示例一樣,在某些情況下,我們需要從完整的句子或段落中獲取一個或多個子字符串。 現在,讓我們看看如何以3種不同的方式在JavaScript中進行操作。

You can also watch the video version of the example usages here:

您還可以在此處觀看示例用法的視頻版本:

1. substring()方法 (1. The substring( ) Method)

Let’s start with the substring( ) method. This method basically gets a part of the original string and returns it as a new string. The substring method expects two parameters:

讓我們從substring()方法開始。 此方法基本上獲取原始字符串的一部分,并將其作為新字符串返回。 substring方法需要兩個參數:

string.substring(startIndex, endIndex);
  • startIndex: represents the starting point of the substring

    startIndex :代表子字符串的起點

  • endIndex: represents the ending point of the substring (optional)

    endIndex :代表子字符串的終點(可選)

Let’s see the usage in an example. Suppose that we have the example string below:

讓我們在示例中查看用法。 假設下面有示例字符串:

const myString = "I am learning JavaScript and it is cool!";

Now if we set the startIndex as 0 and the endIndex as 10, then we will get the first 10 characters of the original string:

現在,如果將startIndex設置為0,將endIndex設置為10,則將獲得原始字符串的前10個字符:

However, if we set only a starting index and no ending index for this example:

但是,如果在此示例中我們僅設置開始索引而沒有設置結束索引:

Then we get a substring starting from the 6th character until the end of the original string.

然后我們得到一個從第6個字符開始直到原始字符串結尾的子字符串。

Some additional points:

其他一些要點:

  • If startIndex = endIndex, the substring method returns an empty string

    如果startIndex = endIndex,則substring方法將返回一個空字符串
  • If startIndex and endIndex are both greater than the length of the string, it returns an empty string

    如果startIndex和endIndex都大于字符串的長度,則返回一個空字符串
  • If startIndex > endIndex, then the substring method swaps the arguments and returns a substring, assuming as the endIndex > startIndex

    如果startIndex> endIndex,則子字符串方法交換參數并返回一個子字符串,假定為endIndex> startIndex

2. slice()方法 (2. The slice( ) Method)

The slice( ) method is similar to the substring( ) method and it also returns a substring of the original string. The slice method also expects the same two parameters:

slice()方法類似于substring()方法,并且它還返回原始字符串的子字符串。 slice方法還需要相同的兩個參數:

string.slice(startIndex, endIndex);
  • startIndex: represents the starting point of the substring

    startIndex :代表子字符串的起點

  • endIndex: represents the ending point of the substring (optional)

    endIndex :代表子字符串的終點(可選)

substring()和slice()方法的共同點: (The common points of substring( ) and slice( ) methods:)

  • If we don’t set an ending index, then we get a substring starting from the given index number until the end of the original string:

    如果我們沒有設置結束索引,那么我們將從給定的索引號開始直到原始字符串的末尾得到一個子字符串:
  • If we set both the startIndex and the endIndex, then we will get the characters between the given index numbers of the original string:

    如果我們同時設置了startIndex和endIndex,則將獲得原始字符串的給定索引號之間的字符:
  • If startIndex and endIndex are greater than the length of the string, it returns an empty string

    如果startIndex和endIndex大于字符串的長度,則返回一個空字符串

slice()方法的區別: (Differences of the slice( ) method:)

  • If startIndex > endIndex, the slice( ) method returns an empty string

    如果startIndex> endIndex,則slice()方法返回一個空字符串
  • If startIndex is a negative number, then the first character begins from the end of the string (reverse):

    如果startIndex為負數,則第一個字符從字符串的末尾開始(反向):

Note: We can use the slice( ) method also for JavaScript arrays. You can find here my other article about the slice method to see the usage for arrays.

注意:我們也可以將slice()方法用于JavaScript數組。 您可以在此處找到有關slice方法的其他文章 ,以了解數組的用法。

3. substr()方法 (3. The substr( ) Method)

According to the Mozilla documents, the substr( ) method is considered a legacy function and its use should be avoided. But I will still briefly explain what it does because you might see it in older projects.

根據Mozilla文檔 ,substr()方法被視為舊版函數,應避免使用它。 但是我仍然會簡要解釋它的作用,因為您可能會在較早的項目中看到它。

The substr( ) method also returns a substring of the original string and expects two parameters as:

substr()方法還返回原始字符串的子字符串,并期望兩個參數為:

string.substring(startIndex, length);
  • startIndex: represents the starting point of the substring

    startIndex :代表子字符串的起點

  • length: number of characters to be included (optional)

    length :要包含的字符數(可選)

You can see the difference here: the substr( ) method expects the second parameter as a length instead of an endIndex:

您可以在此處看到區別:substr()方法將第二個參數作為長度而不是endIndex:

In this example, it basically counts 5 characters starting with the given startIndex and returns them as a substring.

在此示例中,它基本上從給定的startIndex開始計數5個字符,并將它們作為子字符串返回。

However, if we don’t define the second parameter, it returns up to the end of the original string (like the previous two methods do):

但是,如果我們不定義第二個參數,它將返回到原始字符串的末尾(就像前兩個方法一樣):

Note: All 3 methods return the substring as a new string and they don’t change the original string.

注意:所有3種方法都將子字符串作為新字符串返回,并且它們不會更改原始字符串。

結語 (Wrap up)

So these are the 3 different methods to get a substring in JavaScript. There are many other built-in methods in JS which really help us a lot when dealing with various things in programming. If you find this post helpful, please share it on social media.

因此,這是在JavaScript中獲取子字符串的3種不同方法。 JS中還有許多其他內置方法,在處理編程中的各種問題時,它們確實對我們有很大幫助。 如果您發現此帖子有幫助,請在社交媒體上分享。

If you want to learn more about web development, feel free to follow me on Youtube!

如果您想了解有關Web開發的更多信息,請隨時 在YouTube上關注我

Thank you for reading!

感謝您的閱讀!

翻譯自: https://www.freecodecamp.org/news/javascript-substring-examples-slice-substr-and-substring-methods-in-js/

js字符串slice

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/390523.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/390523.shtml
英文地址,請注明出處:http://en.pswp.cn/news/390523.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

leetcode 218. 天際線問題

城市的天際線是從遠處觀看該城市中所有建筑物形成的輪廓的外部輪廓。給你所有建筑物的位置和高度,請返回由這些建筑物形成的 天際線 。 每個建筑物的幾何信息由數組 buildings 表示,其中三元組 buildings[i] [lefti, righti, heighti] 表示&#xff1a…

[Android Pro] 終極組件化框架項目方案詳解

cp from : https://blog.csdn.net/pochenpiji159/article/details/78660844 前言 本文所講的組件化案例是基于自己開源的組件化框架項目github上地址github.com/HelloChenJi…其中即時通訊(Chat)模塊是單獨的項目github上地址github.com/HelloChenJi… 1.什么是組件化&#xff…

如何寫一個vue指令directive

舉個例子 :clickoutside.js const clickoutsideContext clickoutsideContext;export default {/*param el 指令所綁定的元素param binding {Object} param vnode vue編譯生成的虛擬節點*/bind (el, binding, vnode) {const documentHandler function(e) {console.…

安裝angular cli_Angular 9適用于初學者—如何使用Angular CLI安裝第一個應用程序

安裝angular cliAngular is one of the most popular JavaScript frameworks created and developed by Google. In the last couple of years, ReactJS has gained a lot of interest and has become the most popular modern JS library in the industry. But this doesn’t …

leetcode 1818. 絕對差值和

給你兩個正整數數組 nums1 和 nums2 &#xff0c;數組的長度都是 n 。 數組 nums1 和 nums2 的 絕對差值和 定義為所有 |nums1[i] - nums2[i]|&#xff08;0 < i < n&#xff09;的 總和&#xff08;下標從 0 開始&#xff09;。 你可以選用 nums1 中的 任意一個 元素來…

【轉載】keil5中加入STM32F10X_HD,USE_STDPERIPH_DRIVER的原因

初學STM32&#xff0c;在RealView MDK 環境中使用STM32固件庫建立工程時&#xff0c;初學者可能會遇到編譯不通過的問題。出現如下警告或錯誤提示&#xff1a; warning: #223-D: function "assert_param" declared implicitly;assert_param(IS_GPIO_ALL_PERIPH(GPIOx…

下崗職工_下崗后我如何獲得多位軟件工程師的面試

下崗職工“Opportunities to find our deeper powers come when life seems most challenging.” -Joseph Campbell“當生活似乎最具挑戰性時&#xff0c;就有機會找到我們更深層的力量。” 約瑟夫坎貝爾 I was recently laid off for the first time in my life. I realized t…

1846. 減小和重新排列數組后的最大元素

給你一個正整數數組 arr 。請你對 arr 執行一些操作&#xff08;也可以不進行任何操作&#xff09;&#xff0c;使得數組滿足以下條件&#xff1a; arr 中 第一個 元素必須為 1 。任意相鄰兩個元素的差的絕對值 小于等于 1 &#xff0c;也就是說&#xff0c;對于任意的 1 <…

bashdb常用命令

一、列出代碼和查詢代碼類&#xff1a; l 列出當前行以下的10行- 列出正在執行的代碼行的前面10行. 回到正在執行的代碼行w 列出正在執行的代碼行前后的代碼/pat/ 向后搜索pat&#xff1f;pat&#xff1f;向前搜索pat二、Debug控制類&#xff1a; h 幫助help 命令 得到…

podcast播客資源_為什么播客是我的新維基百科-完美的非正式學習資源

podcast播客資源In this article, I’ll explain why podcasts replaced a lot of my Wikipedia usage for informal learning. I’ll also talk about how I listen to 5 hours of podcasts every day.在本文中&#xff0c;我將解釋為什么播客代替了我的許多Wikipedia用于非正…

劍指 Offer 53 - I. 在排序數組中查找數字 I(二分法)

統計一個數字在排序數組中出現的次數。 示例 1: 輸入: nums [5,7,7,8,8,10], target 8 輸出: 2 示例 2: 輸入: nums [5,7,7,8,8,10], target 6 輸出: 0 限制&#xff1a; 0 < 數組長度 < 50000 解題思路 先用二分法查找出其中一個目標元素再向目標元素兩邊查找…

MVC與三層架構區別

我們平時總是將三層架構與MVC混為一談&#xff0c;殊不知它倆并不是一個概念。下面我來為大家揭曉我所知道的一些真相。 首先&#xff0c;它倆根本不是一個概念。 三層架構是一個分層式的軟件體系架構設計&#xff0c;它可適用于任何一個項目。 MVC是一個設計模式&#xff0c;它…

tensorflow 實現邏輯回歸——原以為TensorFlow不擅長做線性回歸或者邏輯回歸,原來是這么簡單哇!...

實現的是預測 低 出生 體重 的 概率。尼克麥克盧爾&#xff08;Nick McClure&#xff09;. TensorFlow機器學習實戰指南 (智能系統與技術叢書) (Kindle 位置 1060-1061). Kindle 版本. # Logistic Regression #---------------------------------- # # This function shows ho…

sdlc 瀑布式 生命周期_SDLC指南–軟件開發生命周期的階段和方法

sdlc 瀑布式 生命周期When I decided to teach myself how to code almost four years ago I had never heard of, let alone thought about, the software development life cycle.當我差不多四年前決定教自己如何編碼時&#xff0c;我從未聽說過軟件開發生命周期&#xff0c;…

劍指 Offer 48. 最長不含重復字符的子字符串

請從字符串中找出一個最長的不包含重復字符的子字符串&#xff0c;計算該最長子字符串的長度。 示例 1: 輸入: “abcabcbb” 輸出: 3 解釋: 因為無重復字符的最長子串是 “abc”&#xff0c;所以其長度為 3。 示例 2: 輸入: “bbbbb” 輸出: 1 解釋: 因為無重復字符的最長子…

Mysql-my-innodb-heavy-4G.cnf配置文件注解

Mysql-同Nginx等一樣具備多實例的特點&#xff0c;簡單的講就是在一臺服務器上同時開啟多個不同的服務端口&#xff08;3306,3307&#xff09;同時運行多個Mysql服務進程&#xff0c;這些服務進程通過不同的socket監聽不同的服務端口來提供服務。這些Mysql多實例公用一套Mysql安…

is 和 == 的區別

is 和 操作符的區別 python官方解釋&#xff1a; 的meaning為equal&#xff1b; is的meaning為object identity&#xff1b; is 判斷對象是否相等&#xff0c;即身份是否相同&#xff0c;使用id值判斷&#xff1b; 判斷對象的值是否相等。id值是什么&#xff1f;id()函數官網…

win10管理凌亂桌面_用于管理凌亂的開源存儲庫的命令行技巧

win10管理凌亂桌面Effective collaboration, especially in open source software development, starts with effective organization. To make sure that nothing gets missed, the general rule, “one issue, one pull request” is a nice rule of thumb.有效的協作(特別是…

JAVA數組Java StringBuffer 和 StringBuilder 類

版權聲明&#xff1a;本文為博主原創文章&#xff0c;未經博主允許不得轉載。 https://blog.csdn.net/qq_34173549/article/details/80215173 Java StringBuffer 和 StringBuilder 類 當對字符串進行修改的時候&#xff0c;需要使用 StringBuffer 和 StringBuilder 類。 和 Str…

strlen和sizeof的長度區別

strlen返回字符長度 而sizeof返回整個數組占多長&#xff0c;字符串的\0也會計入一個長度轉載于:https://www.cnblogs.com/DawaTech/p/8086055.html