views:

135

answers:

4

I need to replace text entered in textarea with other characters, that I will call. For example, I need to replace the text, that I will enter to the textarea by clicking some button calls "change text" using JavaScript and it will change, for example, character "a" to "1", "b" to "2", "c" to "3" etc.

A: 
// Replaces all instances of the given substring.
String.prototype.replaceAll = function( 
    strTarget, // The substring you want to replace
    strSubString // The string you want to replace in.
    ){
    var strText = this;
    var intIndexOfMatch = strText.indexOf( strTarget );

    // Keep looping while an instance of the target string
    // still exists in the string.
    while (intIndexOfMatch != -1){
     // Relace out the current instance.
     strText = strText.replace( strTarget, strSubString )

     // Get the index of any next matching substring.
     intIndexOfMatch = strText.indexOf( strTarget );
    }

    // Return the updated string with ALL the target strings
    // replaced out with the new substring.
    return( strText );
}
streetparade
A: 

If your just looking for a nudge in the right direction, look at string replace.

String Replace

Sivvy
+1  A: 
// get the value of the textarea
var textarea = document.getElementById('id_of_the_textarea');
var value = textarea.value;
// define an array of replacements
var replacements = [
    { from: 'a', to: '1' }, 
    { from: 'b', to: '2' }, 
    { from: 'c', to: '3' }
];
// loop through the array of replacements
for (var i = 0, replacement; i < replacements.length, replacement = replacements[i]; i++) {
    // replace
    value = value.replace(replacement.from, replacement.to);
}
// replace the old text with the new
textarea.value = value;
Darin Dimitrov
A: 

You might find it more efficient to use the replace signature that takes a regular expression match and a function, rather than iterating with multiple passes of String.replace.

peller