Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why won't slice work?

Tags:

javascript

I'm new to Javascript, and I'm trying to write a chrome extension.

For the extension, if users input a string, I want the first two characters to be sliced off.

Currently, I have:

if (text.charAt(0) == '/') {
    text.slice(0,2);
    chrome.tabs.create({
        url: "PrivateURL" + text
    });
} 

But it's not working, nothing is being sliced off. I have a feeling something is wrong with my syntax, as I'm still learning. Any help is appreciated.

like image 994
HDCerberus Avatar asked Oct 21 '25 23:10

HDCerberus


1 Answers

Slice does not work "in place" but returns the value:

var text = "Hello World";
console.log(text.slice(0,2));
// He
console.log(text);
// Hello World    (unchanged!)

You need to assign it to the variable like this:

text = text.slice(0,2);

Also, from your question, it sounds as if you're trying to remove the first two letters. That would be

var text = "Hello World";
text = text.slice(2);
// will be "llo World"
like image 112
amenthes Avatar answered Oct 24 '25 13:10

amenthes