1

Is it possible to get the value of a text input and replace part of it only?

For example, let's say I have:

$("#myTextInput").val("hello sunshine!");

And I would like to replace "hello" with "good morning" WITHOUT erasing "sunshine"... Is that possible? Any help is greatly appreciated, thank you in advance!

  • 1
    Possible duplicate of [How do I do string replace in JavaScript to convert ‘9.61’ to ‘9:61’?](http://stackoverflow.com/questions/2145988/how-do-i-do-string-replace-in-javascript-to-convert-9-61-to-961) – swajak Apr 21 '16 at 02:22

1 Answers1

2

You can use val() with callback and update based on old value

$("#myTextInput").val(function(index, oldVal) {
  return oldVal.replace('hello', 'good morning');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="myTextInput" value="hello abc" />
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188