What is the difference between slice() and substr() in JavaScript?
They have different signatures, .slice()
is:
string.slice(beginIndex, endIndex)
Whereas .substr()
is:
string.substr(beginIndex, length);
So for example, if we have "1234"
and wanted "23"
, it would be:
"1234".slice(1,3)
//or...
"1234".substr(1,2)
They also have different behavior for the more-rarely used negative indexes, look at the MDC documentation for .slice()
and .substr()
for full descriptions.
Substring vs Slice vs Other?
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">
Why two different methods slice() & substring()?
Even though it looks superficially like slice
and substring
do the same thing, the big difference is in how they handle negative arguments.
When JavaScript was first created in Netscape 2.0, there was just a substring
method. If either of its arguments are negative, they are treated as 0.
When JavaScript 1.2 was introduced with Netscape 4.0, they wanted to add the behavior of allowing negative indexes to mean distances from the end of the string. They couldn't change substring
to have this new behavior because it would break backward compatibility with scripts that expected negative indexes to be treated as 0, so they had to create a new function to support the added feature. This function was called slice
, and was implemented on Array
as well as String
.
Another, smaller difference is that with substring
the order of the arguments doesn't matter, so substring(1, 4)
is the same as substring(4, 1)
. With slice
, order does matter, so slice(4, 1)
will just yield an empty string.
String.slice and string.substring
I figured it out:
var str = document.getElementById("fullName").value;
var space = str.indexOf(" ");
var firstname = str.slice(0, space);
var lastname = str.substr(space);
Thank you all!
What are the differences between substr method and slice method in this exercise?
You have to be aware that .slice(7, 10)
method will return letters starting from 7
index up to 10
index (excluding the letter on with 10th
index).
var newStringMethod = 'lets try a subslice method on this string primitive data type variable';console.log(newStringMethod.slice(7, 10));
What is the difference between substr and substring?
The difference is in the second argument. The second argument to substring
is the index to stop at (but not include), but the second argument to substr
is the maximum length to return.
Links?
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substr
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substring
What is the difference between String.subString() and String.subSequence()
Using str.subSequence(begin, end)
returns a CharSequence which is a read-only form of the string represented as a sequence of chars.
For example:
String string = "Hello";
CharSequence subSequence = string.subSequence(0, 5);
It's read only in the sense that you can't change the chars
within the CharSequence
without instantiating a new instance of a CharSequence
.
If you have to use str.subSequence(begin, end)
, you can cast the result to a String
:
String string = "Hello";
String subSequence = (String) string.subSequence(0, 5);
and use all the normal String
operators like subSequence += " World";
What is a difference between these two slice copy approaches in Go
Your "No.1" approach appends to a nil
slice which guarantees that a new backing array will be allocated if there are more than zero params provided.
Your "No.2" approach doesn't create a new slice, it just slices the param.
If Assign()
is called by passing an existing slice, the 2nd approach will store that, and if its elements are modified, it will be reflected in the stored slice.
Let's modify your example a little to test it:
type T1 struct {
local []string
}
func (t *T1) Assign1(param ...string) {
t.local = nil
t.local = append(t.local, param...) // No.1 <<<
}
func (t *T1) Assign2(param ...string) {
t.local = nil
t.local = param[:] // No.2 <<<
}
Testing it:
t1 := &T1{}
s := []string{"a", "b", "c"}
t1.Assign1(s...)
fmt.Println(t1.local)
s[0] = "x"
fmt.Println(t1.local)
s = []string{"a", "b", "c"}
t1.Assign2(s...)
fmt.Println(t1.local)
s[0] = "x"
fmt.Println(t1.local)
Output (try it on the Go Playground):
[a b c]
[a b c]
[a b c]
[x b c]
As you can see, when using Assing1()
, the local
slice is not affected by modifying the passed slice.
When using Assing2()
, elements of the local
slice reflect the changes made in the original.
Please read relevant blog posts:
The Go Blog: Go Slices: usage and internals
The Go Blog: Arrays, slices (and strings): The mechanics of 'append'
Related Topics
Check If an Array Is Empty or Exists
How to Add an Object to an Array
JavaScript - Get Minutes Between Two Dates
How to Add Conditional Attribute in Angular 2
JavaScript Math, Round to Two Decimal Places
Get the Value of Checked Checkbox
Ajax, Back Button and Dom Updates
Can Es6 Template Literals Be Substituted at Runtime (Or Reused)
Nodejs Callbacks Simple Example
How to Calculate Md5 Hash of a File Using JavaScript
Angularjs Changes Urls to "Unsafe:" in Extension Page
How to Check If an Element Is Really Visible with JavaScript
How to Get the Day of Week and the Month of the Year
Removing Event Listener Which Was Added with Bind
Dangerous Implications of Allman Style in JavaScript
JavaScript Document.Write Replaces All Body Content When Using Ajax
How to Differentiate Single Click Event and Double Click Event