1

I'm trying to achieve the below Java selection in Javascript, and I'm a little stumped at the moment...

Java:

String input = inputField.getText();

foreach (char c: input.toCharArray()){
    input = input.replace('a','1');
    input = input.replace('b','2');
    //and so on...
}
return input;
}

This is what I've tried:

var input = document.getElementById('inputField').value; //input field is textarea

for(var i = 0; i < input.length; i++){
    for(input.charAt(i)){
        input = input.replace('a','1');
        input = input.replace('b','2');
    }
}
return input;
}

I've also tried some different variations, such as disregarding the loop entirely and just using replace; however, then the replaces will just fire off sequentially and will not cover the length of long multi spaced strings.

Any help on this would be greatly appreciated. Thanks!

execv3
  • 312
  • 1
  • 4
  • 14
  • 3
    Your code (java one) doesn't make any sense to me. Same as replacing all chars to 'z' – realUser404 Nov 30 '14 at 23:07
  • Are you trying achieve something like a [Caesar cipher](http://en.wikipedia.org/wiki/Caesar_cipher)? – James Nov 30 '14 at 23:20
  • My Java code summed up. "For every character in this string; replace x character with y character and return it" I've ran my Java code before and it works for what I need it to do. I just need to write a ha equivalent. – execv3 Nov 30 '14 at 23:24

2 Answers2

0

As realUser404 said, your code doesn't do what you want to to do anyway.

Here is, what I assume you want (incrementing each char in the string by 1), in Javascript.

var inputString = "abcdefg",
    outputString = "";

for (var i = 0; i < inputString.length; i++) {
    outputString += String.fromCharCode(inputString.charCodeAt(i) + 1);
}
Michael Fry
  • 1,090
  • 9
  • 12
0

The replace function in JavaScript just replaces the first occurrence. A similar post is How to replace all occurrences of a string in JavaScript?.

What you should use is RegExp:

s = 'abcabc';
s = s.replace(/a/g, 'b');

Check out the code here: JSFiddle.

Community
  • 1
  • 1
Joy
  • 9,430
  • 11
  • 44
  • 95