0

I'm not sure if this is a stupid question but can I write something that returns a substring without using substrings?

for e.g. usually you'd write something like this:

var str = "Hello world";
var res = str.substring(1, 4);

Can i use a loop instead to do it? Or is that not possible? How would i start to do it? I know it's something to do with arrays.

would it be something like A[i] and adding loops?

4
  • You can...It is possible...Use += for concatenation...Try this: var str = "Hello world"; var op = ''; for (var i = 1; i < 4; i++) { op += str[i]; } alert(op); var res = str.substring(1, 4); alert(res); Commented Feb 18, 2016 at 10:18
  • 2
    A string like var str = "Hello world" can be treated as an array. So, if you run str[0] you will get "H". Commented Feb 18, 2016 at 10:22
  • It is not a stupid question but may I ask why you would try to do this? Commented Feb 18, 2016 at 10:23
  • 1
    @RayonDabre That's fantastic, just what i needed thank you! Commented Feb 18, 2016 at 10:48

2 Answers 2

2

You could do something like this if you really want to use an array and indexes:

var str = "Hello world";
var res = "";
var first_char = 1; // inclusive
var last_char = 4; // exclusive


for(var i = first_char; i < last_char; i++) {
	res += str[i];
}

alert(res);

Sign up to request clarification or add additional context in comments.

Comments

0

but can I write something that returns a substring without using substrings?

Not sure why you don't want to use substring, hope there is no issue with slice

str.slice(1,5); //outputs "ello"

or, if you want to make it more complicated then

str.split("").splice(1,4).join(""); //outputs "ello"

this one treats str as array and then filter out the data based on index

str.split("").filter( function(value, index){ if ( index >= 1 && index < 5 ) {return true;} else {return false;} } ).join(""); //outputs "ello"

2 Comments

I'm not sure, but I think the question is a learning exercise.
I'm missing a jQuery solution!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.