0

i know there are similar threads but i have tried what you suggested there but still couldn´t solve my problem.

for(var i = text.length-1; i>=0; i--)
    {
        if(text.charCodeAt(i) < 42 || text.charCodeAt(i) > 57)
        {
            text.splice(i,1);
        }
    }
    alert(text);

Why is alert(text); not executed? Something is wrong with the Splice, please help me.

7
  • 3
    @AbdennourToumi Java != JavaScript Commented Jun 2, 2014 at 19:07
  • 1
    @AbdennourToumi possible confusion of lanaguage.. Java != JavaScript Commented Jun 2, 2014 at 19:08
  • oh . yes .... you are right Commented Jun 2, 2014 at 19:08
  • make a JSFIDDLE.NET and look in the console Commented Jun 2, 2014 at 19:09
  • You're working with a string. There is no splice method for strings. Commented Jun 2, 2014 at 19:10

3 Answers 3

3

It's because the string in javascript doesn't have a splice method. You need to convert it in an array.

text = text.split('');
text.splice(i,1);
text = text.join('');

And, as an array, you can't use the method charAt but

if(text[i] < 42 || text[i] > 57)

Talking about what's the best way to achieve this task, I would rather suggest to have a look at different solutions way better than this, performance wise.

Here you can find a benchmark where you can see how using the string method slice is way more performant.

http://jsperf.com/split-or-slice-for-string-splice/2

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

2 Comments

Converting it to an array works, but sounds like overkill. How about function splice(string, index, howMany) { return string.substring(0, index) + string.substring(index + howMany);}
yes I could be another solution. I just answered his question wondering why the alert wasn't been executed. That was because of the javascript error in the for loop. Going forward, it's plenty of different solutions to solve this particular task. Thank you!
0

You might be looking for the .slice() method.

text.slice(i,1);

Comments

-4

The alert is not executed because you did not declare it in the beginning of your script.

var text = [];

for(var i = text.length-1; i>=0; i--)
    {
        if(text.charCodeAt(i) < 42 || text.charCodeAt(i) > 57)
        {
            text.splice(i,1);
        }
    }
    alert(text);

1 Comment

text is obviously a string and not an empty array

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.