Javascript Replace

seaside

New Member
Messages
14
Reaction score
0
Points
0
Ok so I am trying to make a textbox that you can write a sentence, and then hit a button. Then the text in the textbox will change certain words to certain other words.

Ex: You write "Hello my name is John Smith." and hit the button. Then the text is changed to "Hi my name was John Smith."

Something like that. So that I can choose words like "hello" and "is", and have them changed to "Hi" and "was".

I have a starting point, but do not know how to put in the textbox, or how to match up words to replace.

I know the replace() method exists, but how would I do this?

Thanks.
 

seaside

New Member
Messages
14
Reaction score
0
Points
0
Thanks Diable, but could you write some code to show wat i should put in my page to get the example above. I didn't understand the atricle.
 

diabolo

Community Advocate
Community Support
Messages
1,682
Reaction score
32
Points
48
you're going to have to pay me for that
=)

no im just kidding, let me write it up, and i'll post it when im done
 

seaside

New Member
Messages
14
Reaction score
0
Points
0
Thanks sooo much. Il up ur rep! lol.

Thanks.

Please remember the textbox and button. Thanks
 

scopey

New Member
Messages
62
Reaction score
0
Points
0
HTML:
<div id="text">Hello my name is John Smith</div><button onclick="tmod('text')">Click</button>

Javascript:
function tmod(id){
var str = document.getElementById(id).innerHTML;
str = str.replace("is","was");
str = str.replace("Hello","Hi");
document.getElementById(id).innerHTML = str;
}

Oh and for a text box, it'll be

HTML:
<input type='text' id="text" value="Hello my name is John Smith" /><button onclick="tmod('text')">Click</button>

Javascript:
function tmod(id){
var str = document.getElementById(id).value;
str = str.replace("is","was");
str = str.replace("Hello","Hi");
document.getElementById(id).value = str;
}
 
Last edited:

seaside

New Member
Messages
14
Reaction score
0
Points
0
thank you. Can I have an E-mail for any later questions?
Edit:
Is there any way, also, to allow the user to have several input boxes that they can write which words are changed to which. Ex: I could write in one box "Dog" and "Cat" in the next. So people can change their words?

Thnx again.
 
Last edited:

xav0989

Community Public Relation
Community Support
Messages
4,467
Reaction score
95
Points
0
Do mean that the user could enter their own list of replacement pairs?
 

scopey

New Member
Messages
62
Reaction score
0
Points
0
I'm not quite sure what you mean sorry.

If you want an interface where users can enter text, then choose what word to replace with what, you could do something like this:

HTML:
<input type='text' id='input1' /><input type='text' id='input1str' /><input type='text' id='input1rep' /><button onclick="tmod('input1')">Click</button>

Javascript:
function tmod(id){
var str = document.getElementById(id).value;
var strstr = document.getElementById(id+"str").value;
var strrep = document.getElementById(id+"rep").value;
str = str.replace(strstr,strrep);
document.getElementById(id).value = str;
}

I hope that's what you meant.

If you want users to be able to define multiple strings to replace, the following should work (I'm just writing and not actually testing, if the code doesn't work, give me a yell and I'll fix it):

(Tell users to seperate the strings with commas)

function tmod(id){
var str = document.getElementById(id).value;
var strstrs = document.getElementById(id+"str").value.split(",");
var strreps = document.getElementById(id+"rep").value.split(",");
var alen = strstrs.length;
var i=0;
for(i=0;i<alen;i++){
if(strstrs && strreps){
str = str.replace(strstrs,strreps);
}
else{
break;
}
}
document.getElementById(id).value = str;
}

Edit: Forgot a semicolon....
 
Last edited:

seaside

New Member
Messages
14
Reaction score
0
Points
0
wow! Thanks! The first one is fantastic.

One last thing if you could.

How do I make the words that they can enter NOT case sensitive. In the first script i know about the /i, but in the newer one you wrote, how would I do this. Again, Thanks!
 

scopey

New Member
Messages
62
Reaction score
0
Points
0
Javascript has a .toLowerCase() property, the only fallback of this is that your output string will not keep the case formatting of the original string, without a needlessly complicated script.

So, if you want cases to not be a problem:

Javascript:
function tmod(id){
var str = document.getElementById(id).value.toLowerCase();
var strstr = document.getElementById(id+"str").value.toLowerCase();
var strrep = document.getElementById(id+"rep").value.toLowerCase();
str = str.replace(strstr,strrep);
document.getElementById(id).value = str;
}

If you want to always capitalize the first character of the string, then you could use:

function tmod(id){
var str = document.getElementById(id).value.toLowerCase();
var strstr = document.getElementById(id+"str").value.toLowerCase();
var strrep = document.getElementById(id+"rep").value.toLowerCase();
str = str.replace(strstr,strrep);
var astr = str.split("",2);
var letter = astr[0].toUpperCase();
str = letter+str.substr(1);
document.getElementById(id).value = str;
}
 

descalzo

Grim Squeaker
Community Support
Messages
9,373
Reaction score
326
Points
83
With changes to the original text and change pairs....

Originally Posted by scopey
HTML:
<div id="text">I have a cat and a dog</div><button onclick="tmod('text')">Click</button>

Javascript:
function tmod(id){
var str = document.getElementById(id).innerHTML;
str = str.replace("cat","hounddog");
str = str.replace("dog","kitten");
document.getElementById(id).innerHTML = str;
}

I don't think the outcome is what is expected.
 
Last edited:

seaside

New Member
Messages
14
Reaction score
0
Points
0
Oh and more importantly, how can i have more than one replacement set that the user can edit? Lets say... 10? like they can put in their own, up to ten times? Thanks. And how do I make them NOT case sensitive.
 

scopey

New Member
Messages
62
Reaction score
0
Points
0
@descalzo:

Hehe, well spotted. That's an annoying case.

I'll try to come up with a work around.

@seaside:

The toLowerCase bit posted above shooould work for the case sensitivity. If you're copying and pasting, make sure that no spaces are in the code. I forgot to put the code tags around my code so this forum automatically puts spaces in long strings.

For multiple replacements, I posted a method earlier:

Code:
function tmod(id){
var str = document.getElementById(id).value;
var strstrs = document.getElementById(id+"str").value.split(",") ;
var strreps = document.getElementById(id+"rep").value.split(",") ;
var alen = strstrs.length;
var i=0;
for(i=0;i<alen;i++){
if(strstrs[i] && strreps[i]){
str = str.replace(strstrs[i],strreps[i]);
}
else{
break;
}
}
document.getElementById(id).value = str;
}

This works by writing your string in the first field, then writing all the words you want replaced in the second field, seperated by commas, and then writing all the words you want to be put in, seperated by commas, and respective to the words in the second text box. If you want it to be more userfriendly, and have individual boxes for each replacement, that should be possible, but I don't have to time to write that code right now sorry.

But if I put it all together:

Code:
function tmod(id){
var str = document.getElementById(id).value;
var strstrs = document.getElementById(id+"str").value.split(",") ;
var strreps = document.getElementById(id+"rep").value.split(",") ;
var alen = strstrs.length;
var i=0;
for(i=0;i<alen;i++){
if(strstrs[i] && strreps[i]){
str = str.replace(strstrs[i].toLowerCase(),strreps[i].toLowerCase());
}
else{
break;
}
}
var astr = str.split("",2);
var letter = astr[0].toUpperCase();
str = letter+str.substr(1);
str = str.replace(" i "," I ");
document.getElementById(id).value = str;
}
 
Last edited:

seaside

New Member
Messages
14
Reaction score
0
Points
0
Oh and more importantly, how can i have more than one replacement set that the user can edit?
Lets say... 10?
like they can put in their own, up to ten times?

Thanks.


And how do I make them NOT case sensitive?
Edit:
Thanks All! Real cool!
 
Last edited:

descalzo

Grim Squeaker
Community Support
Messages
9,373
Reaction score
326
Points
83
@descalzo:

Hehe, well spotted. That's an annoying case.

I'll try to come up with a work around.

And where you want

California --> Alabama
for--> because

What happens to the phrase
"I live in California"

Or
cat -> tabby
catsup -> condiment

what happens to

"I like catsup on my hot dog"

:biggrin:

The standard requirement for replacements is that the first/longest match is replaced first. Then you repeat the process starting after the replacement text, not from the beginning of the string.


Basic idea:


Code:
// one array of original words to match and one for the replacements
 
    var original_words = [ 'fox' , 'Cat' , 'cattail' ,   'fox' , 'bear' ];
    var replacement_words = [ 'kit' , 'kitten' , 'plant' ,  'cub' ];
    var str = "I have a cattail and a dog and a Fox." ;
 
    function wordsearch(){
       var pat = '';
       var i = original_words.length ;
       var result = '' ;
       var working_copy = str ;
       while( working_copy.length > 0 ){
           var min_pos = 100000000 ;   // assuming string is shorter than this...
           var max_length = -1 ;            // keep track of longest match
           var best_pat = '' ;                  // pattern of best match
           var replacement_index = -1 ;  // index into replacement_words array 
           for( j=0; j< i ; j++){
              pat = original_words[ j ] ;           // check for one word at a time
              regexp = new RegExp(pat, 'i');   // drop the 'i' if you want it case sensitive
              pos = working_copy.search( regexp ) ;  
              if( pos > -1 ){                   // find it?
                  if( pos < min_pos ){      // earlier match ?
                     min_pos = pos ;
                     max_length = pat.length ;
                     best_pat = regexp ;
                     replacement_index = j ;
                  } else {
                      if( pos == min_pos ){   // a tie? 
                          if( pat.length > max_length ){  // tie, but a longer match?
                              min_pos = pos ;
                              max_length = pat.length ;
                              best_pat = regexp ;
                              replacement_index = j;
                          }
                      }
                  }
               }
           } 
           if( max_length < 0 ){ // no match on any try, finish up.
              result = result + working_copy ;
              working_copy = '' ;
           } else {
              // make the replacement
              working_copy = working_copy.replace( best_pat , replacement_words[ replacement_index ] );
              // add the replaced text to the growing result
              result = result + working_copy.substring( 0, min_pos + replacement_words[ replacement_index ].length )
              // chop of the part we have already searched & replaced
              working_copy = working_copy.substring( min_pos + replacement_words[ replacement_index ].length ) ;
           }
         }
 
       alert( result ) ;
    }

Works for the test case. No guarantees.
 
Top