Picking the first characters of a string

Asked

Viewed 31,518 times

7

How I replace a string in Javascript?

I’m taking the name of the page.

var str = window.location.pathname;

The name of the url is "/checkout/9/finalizacao" I want to change to "/checkout/"

In the first 10 characters.

I know there is the sub string method, but I don’t know how to use it.

You don’t have to put in complicated code, just the function I use to get the first 10 characters and how to implement it. ('Cause I’m gonna use it on an if later)

if (pageName == "/carrinho/index" || str == "/checkout/"){
}

2 answers

11


Exactly, you can use the .substring to get the first 10 characters:

var str = window.location.pathname;
alert(str.substring(0,10));//intervalo de caracteres prentendido
  • It worked, I used: var str = window.location.pathname; str = str.substring(0,10);

  • That’s right, you get the value on str how do you intend :)

5

In this case I would separate the strings from the URL and check the value.

// Separa a string a partir do char "/" e retorna o 1 valor

var str = window.location.pathname.split('/')[1]

if (pageName == "/carrinho/index" || str == "checkout"){
}

Browser other questions tagged

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