Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

substring javascript not working at all

Tags:

javascript

is there any reason why this wouldn't be working?

     var caseString = "sliderInput";
     var theString = caseString.substring(1, 2);

I put it through the Firebug debugger in Firefox and it is giving me the error: "invalid assignment left-hand side."

** here is my exact code

        var elements = new Array();
        elements = document.getElementsByTagName("Input");


var allSliderInputs = new Array();
var sliderParams = new Array();
var first, last, inc, style;

for (var i=0; i < elements.length ; i++){
    var c = elements[i].className; //works fine here
    var t = c.substring(0, 2); //when it hits this line it says "invalid assignment left-hand side"

 }
like image 441
user1066524 Avatar asked Sep 02 '26 00:09

user1066524


2 Answers

substring is 0-indexed so you should instead do something like this:

var word = "slider";
var part = word.substring(0,2); // sl

Also take note that .slice() does the same thing but is actually more powerful, because it can count backwards as well as forwards.

To solve your new problem I would suggest a few things:

  1. You need to cache your length value. The list returned by getElementsByTagName is live meaning any changes to your list while you're looping will effect that value, so it won't behave as you'd expect.
  2. Don't use new Array() it's overly fancy.
  3. You don't need to instantiate variables that you're going to define right after.

Try this:

var elements = document.getElementsByTagName("input");
var allSliderInputs = [];
var sliderParams = [];
var len = elements.length;
var first, last, inc, style, c, t, i;

for (i = 0; i < len; i++) {
    c = elements[i].className; //works fine here
    t = c.substring(0, 2); 
    console.log(t);
}

This works fine for me in Firefox when run on this very page in stackoverflow: sample result

like image 140
Jamund Ferguson Avatar answered Sep 03 '26 14:09

Jamund Ferguson


First, .substring (and .substr) is 0-based, not 1-based.

.substring extracts a string between two positions. E.g. .substring(1,4) returns the 2nd, 3rd, and 4th characters. It will stop at position 4.

.substr extracts a string based on start + length. .substr(1,4) returns the first 4 characters starting with the 2nd character.

like image 35
Joe Avatar answered Sep 03 '26 12:09

Joe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!