简体   繁体   中英

Substring vs Slice vs Other?

According to MDN, substr is considered legacy code that may eventually become deprecated.

Hence I'm wondering whether substring or slice is better suited for inserting strings into other strings at specific indices?

Or is there another method that is actually intended for this very purpose?

What I'm doing is detecting user input via keydown , which I then, in some cases, intercept and extrapolate to manually pass on the value.

input.onkeydown = function(e){
  if (e.key === 'x'){
    return false
  }
  this.value = // insert character at this.selectionEnd into this.value
  return false
}

The reason I'm doing this is so that I can manage and restrict user input while guaranteeing the output is formatted in a particular way. In other words, the user will not have to format his/her input.

The difference between them is :

The substring() method swaps its two arguments if indexStart is greater than indexEnd, meaning that a string is still returned. The slice() method returns an empty string if this is the case.

If either or both of the arguments are negative or NaN, the substring() method treats them as if they were 0.

slice() also treats NaN arguments as 0, but when it is given negative values it counts backwards from the end of the string to find the indexes.

Since you already have a reference to the string as this.value , and since you can calculate the lower and upper indicies directly (without passing negative indicies or NaN, or anything silly like that), it makes absolutely no difference whether you use substring or slice if you want to insert a particular character. Use whichever you want, it won't have any effect for an operation like this.

this.value = this.value.slice(0, selectionEnd) + 'z' + this.value.slice(selectionEnd);

or

this.value = this.value.substring(0, selectionEnd) + 'z' + this.value.substring(selectionEnd);

both work fine.

 input.onkeydown = function(e){ const { selectionEnd } = this; this.value = this.value.substring(0, selectionEnd) + 'z' + this.value.substring(selectionEnd); this.selectionEnd = selectionEnd + 1; return false; } 
 <input id="input" value="abc"> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM