The differences between slice(), substr(), substring() of string in JavaScript

Giant ship 2020-11-13 04:02:43
differences slice substr substring string


JavaScript in String Of slice(),substr(),substring() The three difference

something in common

Take a fragment from a given string , And return the new string object of this fragment , And it doesn't change the original string .

Specific differences

slice()

str.slice(beginIndex[, endIndex])
Parameters describe
beginIndex From this index ( With 0 Cardinal number ) Start extracting characters from the original string at ( contain ). If the value is negative , Will be regarded as strLength + beginIndex To view , there strLength Is the length of the string ( for example , If beginIndex yes -3 It is regarded as :strLength - 3)
endIndex Optional . In the index ( With 0 Cardinal number ) It's about ( There are characters under the index , It doesn't contain ) End extracting string . If this parameter is omitted ,slice() It will be extracted all the way to the end of the string . If the parameter is negative , It's seen as strLength + endIndex, there strLength That's the length of the string ( for example , If endIndex yes -3, It is , strLength - 3).

describe

slice() Extract a string from a string and return a new string . Changes in one string do not affect another string . in other words ,slice The original string will not be modified ( Only a new string containing part of the original string will be returned ).

slice() The extracted new strings include beginIndex But does not include endIndex. Here are two examples .

example 1:str.slice(1, 4) Extract the second character to the fourth character ( The index of the extracted character (index) In turn 1、2, and 3).

example 2:str.slice(2, -1) Extract the third character to the last character .


Example

var str1 = 'The morning is upon us.', // str1 The length of length yes 23.
str2 = str1.slice(1, 8),
str3 = str1.slice(4, -2),
str4 = str1.slice(12),
str5 = str1.slice(30);
console.log(str2); // Output :he morn
console.log(str3); // Output :morning is upon u
console.log(str4); // Output :is upon us.
console.log(str5); // Output :""
// A negative value is passed in as the index 
var str = 'The morning is upon us.';
str.slice(-3); // return 'us.'
str.slice(-3, -1); // return 'us'
str.slice(0, -1); // return 'The morning is upon us'

substr()

str.substr(start[, length])

Warning : Even though String.prototype.substr(…) Not strictly abandoned (as in "removed from the Web standards"), But it is considered a legacy function and should be avoided if possible . It's not JavaScript Part of the core language , It may be removed in the future . If you can , Use substring() Replace it .

Parameters describe
start Start extracting the position of the character . If it's negative , Is regarded as strLength + start, among strLength Is the length of the string ( for example , If start by -3, Is regarded as strLength + (-3)).
length Optional . Number of characters extracted .

describe

start It's an index of a character . The index of the first character is 0, The index of the last character is The length of a string minus 1.substr from start Position begins to extract characters , extract length Characters ( Or until the end of the string ).

  1. If start Positive value , And is greater than or equal to the length of the string , be substr Returns an empty string .
  2. If start negative , be substr Think of it as a character index starting at the end of a string . If start Is negative and abs(start) Greater than the length of the string , be substr Use 0 As the index to start extracting .
  3. If length by 0 Or negative value , be substr Returns an empty string . If you ignore length, be substr Extract characters , Until the end of the string .

Example

var str = "abcdefghij";
console.log("(1,2): " + str.substr(1,2)); // (1,2): bc
console.log("(-3,2): " + str.substr(-3,2)); // (-3,2): hi
console.log("(-3): " + str.substr(-3)); // (-3): hij
console.log("(1): " + str.substr(1)); // (1): bcdefghij
console.log("(-20, 2): " + str.substr(-20,2)); // (-20, 2): ab
console.log("(20, 2): " + str.substr(20,2)); // (20, 2):

substring()

str.substring(indexStart[, indexEnd])
Parameters describe
indexStart The index of the first character to be intercepted , The character at the index position is used as the first letter of the returned string .
indexEnd Optional . One 0 Integer to the length of the string , Characters indexed by this number are not included in the intercepted string .

describe : substring Extract from indexStart To indexEnd( barring ) Characters between . Specially :

  • If indexStart be equal to indexEnd,substring Returns an empty string .
  • If omitted indexEnd,substring Extract characters all the way to the end of the string .
  • If any parameter is less than 0 Or for NaN, It's treated as 0.
  • If any parameter is greater than stringName.length, It's treated as stringName.length.
  • If indexStart Greater than indexEnd, be substring The execution effect of is like two parameters swapping . See the following example .

Example

var anyString = "Mozilla";
// Output "Moz"
console.log(anyString.substring(0,3));
console.log(anyString.substring(3,0));
console.log(anyString.substring(3,-3));
console.log(anyString.substring(3,NaN));
console.log(anyString.substring(-2,3));
console.log(anyString.substring(NaN,3));
// Output "lla"
console.log(anyString.substring(4,7));
console.log(anyString.substring(7,4));
// Output ""
console.log(anyString.substring(4,4));
// Output "Mozill"
console.log(anyString.substring(0,6));
// Output "Mozilla"
console.log(anyString.substring(0,7));
console.log(anyString.substring(0,10));
// The following example uses String.length Property to get the reciprocal element of the specified string .
// Obviously, this method is easier to remember , Because you no longer remember the starting position and the final position like the example above .
// Displays 'illa' the last 4 characters
var anyString = 'Mozilla';
var anyString4 = anyString.substring(anyString.length - 4);
console.log(anyString4);
// Displays 'zilla' the last 5 characters
var anyString = 'Mozilla';
var anyString5 = anyString.substring(anyString.length - 5);
console.log(anyString5);

Reference material

  1. String.prototype.slice() - JavaScript | MDN
  2. String.prototype.substr() - JavaScript | MDN
  3. String.prototype.substring() - JavaScript | MDN
  4. JavaScript in substr(),substring(),slice() difference
版权声明
本文为[Giant ship]所创,转载请带上原文链接,感谢

  1. [front end -- JavaScript] knowledge point (IV) -- memory leakage in the project (I)
  2. This mechanism in JS
  3. Vue 3.0 source code learning 1 --- rendering process of components
  4. Learning the realization of canvas and simple drawing
  5. gin里获取http请求过来的参数
  6. vue3的新特性
  7. Get the parameters from HTTP request in gin
  8. New features of vue3
  9. vue-cli 引入腾讯地图(最新 api,rocketmq原理面试
  10. Vue 学习笔记(3,免费Java高级工程师学习资源
  11. Vue 学习笔记(2,Java编程视频教程
  12. Vue cli introduces Tencent maps (the latest API, rocketmq)
  13. Vue learning notes (3, free Java senior engineer learning resources)
  14. Vue learning notes (2, Java programming video tutorial)
  15. 【Vue】—props属性
  16. 【Vue】—创建组件
  17. [Vue] - props attribute
  18. [Vue] - create component
  19. 浅谈vue响应式原理及发布订阅模式和观察者模式
  20. On Vue responsive principle, publish subscribe mode and observer mode
  21. 浅谈vue响应式原理及发布订阅模式和观察者模式
  22. On Vue responsive principle, publish subscribe mode and observer mode
  23. Xiaobai can understand it. It only takes 4 steps to solve the problem of Vue keep alive cache component
  24. Publish, subscribe and observer of design patterns
  25. Summary of common content added in ES6 + (II)
  26. No.8 Vue element admin learning (III) vuex learning and login method analysis
  27. Write a mini webpack project construction tool
  28. Shopping cart (front-end static page preparation)
  29. Introduction to the fluent platform
  30. Webpack5 cache
  31. The difference between drop-down box select option and datalist
  32. CSS review (III)
  33. Node.js学习笔记【七】
  34. Node.js learning notes [VII]
  35. Vue Router根据后台数据加载不同的组件(思考->实现->不止于实现)
  36. Vue router loads different components according to background data (thinking - & gt; Implementation - & gt; (more than implementation)
  37. 【JQuery框架,Java编程教程视频下载
  38. [jQuery framework, Java programming tutorial video download
  39. Vue Router根据后台数据加载不同的组件(思考->实现->不止于实现)
  40. Vue router loads different components according to background data (thinking - & gt; Implementation - & gt; (more than implementation)
  41. 【Vue,阿里P8大佬亲自教你
  42. 【Vue基础知识总结 5,字节跳动算法工程师面试经验
  43. [Vue, Ali P8 teaches you personally
  44. [Vue basic knowledge summary 5. Interview experience of byte beating Algorithm Engineer
  45. 【问题记录】- 谷歌浏览器 Html生成PDF
  46. [problem record] - PDF generated by Google browser HTML
  47. 【问题记录】- 谷歌浏览器 Html生成PDF
  48. [problem record] - PDF generated by Google browser HTML
  49. 【JavaScript】查漏补缺 —数组中reduce()方法
  50. [JavaScript] leak checking and defect filling - reduce() method in array
  51. 【重识 HTML (3),350道Java面试真题分享
  52. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  53. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  54. [re recognize HTML (3) and share 350 real Java interview questions
  55. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  56. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  57. 【重识 HTML ,nginx面试题阿里
  58. 【重识 HTML (4),ELK原来这么简单
  59. [re recognize HTML, nginx interview questions]
  60. [re recognize HTML (4). Elk is so simple