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.

user3700591
  • 195
  • 2
  • 2
  • 5

3 Answers3

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

Stefano Ortisi
  • 5,288
  • 3
  • 33
  • 41
  • 1
    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);}` – Ruan Mendes Jun 02 '14 at 19:18
  • 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! – Stefano Ortisi Jun 02 '14 at 19:28
0

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

text.slice(i,1);
Dan C
  • 35
  • 3
-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);
lfarroco
  • 574
  • 6
  • 14