What is the difference between the string.Slice() method and the string.substring() method?

Asked

Viewed 201 times

5

We know the method string.slice() and the method string.substring() allow extracting a part of a string and creating a new string as a result (without modifying the original string). What differentiates one method from the other since both produce the same result?

  • And then grandpa, no answer was good?

2 answers

2


I asked the question and from there I ran after an answer too inserir a descrição da imagem aqui

As stated in the question "o método string.slice() e o método string.substring() permitem extrair uma parte de uma string e criar uma nova string como resultado (sem modificar a string original)"

However, a useful improvement in string.Slice() is that specifying a final index value relative to the end of the main string is easier.

The use of string.substring() to extract a substring that ends before the end of the string requires some mechanisms, such as the following:

string.substring(4, (string.length-2))

Instead, you can assign a negative number to the second parameter of string.slice() to inform a shift from the end of the string:

string.slice(4, -2)

String method.Lice()

string.slice(indiceInicio [, indiceFim])

Returns: String

  • The second parameter is optional. If omitted and the first parameter is not negative, the returned value will be a string from the initial offset to the end of the main string.
  • if the first parameter is negative and the second is omitted the returned value will be a string from the end.
  • If the second parameter is also negative and larger than the first parameter, the returned value will be as shown below:

      string="os dois parâmetros negativos";
      string.slice(-9, -2)
      do final para o inicio primeiro parâmetro (-9) resulta negativos
      segundo parãmetro (-2) retira da string resultante acima e retorna negativ
    
  • Behold

string="os dois parametros negativos";
var resultado =string.slice(-9, -2);
console.log(resultado);

Below you can test the various situations for string.slice()

var mainString = "Oftalmotorrinolaringologista"
function showResults() {
	var form = document.forms[0]
	var param1 = parseInt(form.param1.options[form.param1.selectedIndex].value)
	var param2 = parseInt(form.param2.options[form.param2.selectedIndex].value)
	if (!param2) {
		form.result1.value = mainString.slice(param1)
	} else {
		form.result1.value = mainString.slice(param1, param2)
	}
}
<table border=1>
<form>
<tr><th>Metodo String</th><th>Metodo Parametros</th><th>Resultado</th></tr>
<tr>
<td>string.substring()</td><td>
(&nbsp;<select name="param1" onChange="showResults()">
	<option value=0>0
	<option value=1>1
	<option value=2>2
	<option value=3>3
	<option value=5>5
	<option value=10>10
	<option value=30>30
	<option value=-1>-1
	<option value=-3>-3
	<option value=-5>-5
	<option value=-10>-10
</select>,
<select name="param2" onChange="showResults()">
    <option>(Não)
    <option value=1>1
    <option value=3>3
    <option value=5>5
    <option value=10>10
    <option value=30>30
    <option value=-1>-1
    <option value=-3>-3
    <option value=-5>-5
    <option value=-10>-10
</select>&nbsp;) </td>
<td><input type="text" name="result1" value="Oftalmotorrinolaringologista" size=25></td>
</tr>
</form>
</table>

String method.substring()

string.substring(indiceA, indiceB)

Returns: String of characters between index values indiceA and indiceB

  • The parameters of this method are the initial and final index values of the main string, from which the excerpt must be removed. An important item to note is that the section reaches it, but does not include the character pointed by the highest index value.

  • It makes no difference which index value in the parameters is higher than the other: the method starts the chunk from the lowest value and continues to (but does not include) the highest value. If the two values are equal, the method returns an empty string; and if you omit the second parameter, the end of the string is considered as the endpoint.

Below you can test the various situations for string.substring()

var mainString = "Oftalmotorrinolaringologista"
function showResults() {
	var form = document.forms[0]
	var param1 = parseInt(form.param1.options[form.param1.selectedIndex].value)
	var param2 = parseInt(form.param2.options[form.param2.selectedIndex].value)
	if (!param2) {
		form.result1.value = mainString.substring(param1)
	} else {
		form.result1.value = mainString.substring(param1, param2)
	}
}
<table border=1>
<form>
<tr><th>Metodo String</th><th>Metodo Parametros</th><th>Resultado</th></tr>
<tr>
<td>string.substring()</td><td>
(&nbsp;<select name="param1" onChange="showResults()">
	<option value=0>0
	<option value=1>1
	<option value=2>2
	<option value=3>3
	<option value=5>5
	<option value=10>10
	<option value=30>30
</select>,
<select name="param2" onChange="showResults()">
    <option>(Não)
    <option value=1>1
    <option value=3>3
    <option value=5>5
    <option value=10>10
    <option value=30>30
    <option value=-1>-1
    <option value=-5>-5
    <option value=-10>-10
</select>&nbsp;) </td>
<td><input type="text" name="result1" value="Oftalmotorrinolaringologista" size=25></td>
</tr>
</form>
</table>

1

slice() works as substring() with some different behaviors.

Syntax

string.Slice(start, stop); string.substring(start, stop);

What they have in common:

If start equals stop: returns an empty string

If stop is omitted: extracts characters to the end of the string

If one of the arguments is longer than the string length, the string length will be used instead.

Distinctions of substring():

If start > stop, then substring will swap these 2 arguments. If one of the arguments is negative or is Nan, it will be treated as 0.

Distinctions of Slice():

If start > stop, Slice() will NOT swap the 2 arguments. If start is negative: sets char at the end of the string, exactly as substr() in Firefox. This behavior is observed in Firefox and IE. If stop is negative: sets stop to: string.length - Math.abs(stop) (original value), except limited to 0 (hence Math.max (0, string.length + stop)) as covered in the ECMA specification .

Source

Browser other questions tagged

You are not signed in. Login or sign up in order to post.