How to use the Slice method with negative values?

Asked

Viewed 79 times

0

For example, I have the following code:

    var name = "maria mendonça maria maria dos santos";
    window.alert(name.slice(-6, 0));

And I want to return saints with negative numbers. How to capture the position of "s"? It was not to be 0 or -0?

  • Of which "s" in sbirthdays you’re talking?

1 answer

1

In this case, to return the first "s" of "saints", you would have to define the second argument with -5:

var name = "maria mendonça maria maria dos santos";
console.log(name.slice(-6, -5));

And to return "saints", it would be enough to omit the second argument:

var name = "maria mendonça maria maria dos santos";
console.log(name.slice(-6));

Because then it will pick up from the 6th character to the end of the string, backwards. The value 0 is not applicable in the second argument.

If you want to take the second "s" -1:

var name = "maria mendonça maria maria dos santos";
console.log(name.slice(-1));

When you want to use negative value, you will not use the indices of the string, only the position backwards starting from number 1 up, negatives:

var name = "maria mendonça maria maria dos santos";

// de trás pra frente:

s = -1
o = -2
t = -3
n = -4
a = -5
s = -6
...
  • There is worth buddy helped a lot in a knew hehe more was really worth!

Browser other questions tagged

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