Get the first few characters of a string

5

How do I replace a string in JavaScript?

I'm getting the page name.

var str = window.location.pathname;

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

In case the first 10 characters.

I know there is the sub string method, however I do not know how to use it.

You do not need to put a complicated code, just the function I use to get the first 10 characters and how to implement it. (I'll use it in an if after)

if (pageName == "/carrinho/index" || str == "/checkout/"){
}
    
asked by anonymous 19.05.2015 / 15:35

2 answers

9

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

var str = window.location.pathname;
alert(str.substring(0,10));//intervalo de caracteres prentendido
    
19.05.2015 / 15:47
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"){
}
    
19.05.2015 / 16:34