Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript remove last word in textarea

Can anyone help me to remove last word from the text area and it will replace with some another word.

Example:

I like my dog

should become

I like my cat

The last word is not always dog.

I'll update my code here

    function KeyCheck(e) {

var KeyID = (window.event) ? event.keyCode : e.keyCode;

switch(KeyID) {
    case 32:
        text2 = document.form1.box1.value;
        text2 = ReplaceLastWord(text2, "cat");
                alert(text2);
    }
}

function ReplaceLastWord(str, newStr) {
   return str.replace(/\w*$/, newStr);
}

I have put alert to check whether it's replaced or not

like image 257
Jonny King Avatar asked Feb 23 '23 10:02

Jonny King


1 Answers

var str = 'I like my dog'; 
var newEndStr = 'cat'; 

function ReplaceLastWord(str, newStr) {
   return str.replace(/\w*$/, newStr);
}

console.log(ReplaceLastWord(str, newEndStr));

output:

I like my cat
like image 63
Kakashi Avatar answered Mar 07 '23 20:03

Kakashi