0

So far I have this which replaces the text in the input box if it has the object name in it, with the object value:

var obj = { '1': 'fish', 'q': 'apple', 'z': 'banana', }; $("#inputBoxID").on("keyup", function() { if(obj.hasOwnProperty($("#inputBoxID").val())) $(this).val(obj[$("#inputBoxID").val()]); }); 

I would like to modify this so that on any occurrence of a object name it would replace the object name with the value, here's an example of what I'm trying to do:

User enters hello q I want that to be replaced with: hello apple

How would I go about doing this?

6
  • 2
    what should happen if user type 'qq'? Commented Mar 16, 2018 at 19:24
  • 1
    or if user type 'hello question1'? Should it replace q,e, and 1? Commented Mar 16, 2018 at 19:25
  • @yajiv it would turn into appleapple Commented Mar 16, 2018 at 20:06
  • @Observer yes it should Commented Mar 16, 2018 at 20:06
  • @newbie there is 'e' in apple, it should replace or not?(means if i write apple then what would be the output) Commented Mar 16, 2018 at 20:21

3 Answers 3

2

You can split by space, map and then join!

var obj = { '1': 'fish', 'q': 'apple', 'e': 'banana'}; $("#inputBoxID").on("keyup", function() { var str = $("#inputBoxID").val().split(' ').map(function(word) { return obj[word] || word; }).join(' '); $(this).val(str); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input id="inputBoxID">

Sign up to request clarification or add additional context in comments.

4 Comments

I can not write any word that starts with q or e or 1
I didnt ask the question bro. Just was an observation
Thanks @Ele how can I modify this so that if someone entered qq it would change into appleapple ?
Do you want to replace every letter who matches with any key in obj?
1

you can simply replace any occurrence of key with it's value, like below(I know it's little heavy as for each key press we are iterating through object).

var obj = { '1': 'fish', 'q': 'apple', 'z': 'banana', }; $("#inputBoxID").on("keyup", function() { var str = $("#inputBoxID").val(); for(var x in obj){ if(obj.hasOwnProperty(x)){ str=str.replace(x,obj[x]); } } $(this).val(str); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input id="inputBoxID" type="text">

Comments

0

You might wanna replace each word separately by splitting the string into an array of words and then replacing it:

 $("#inputBoxID").val((_, v) => v.split(" ").map(word => obj[word] || word).join(" ")) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.