jitendrapurohit jitendrapurohit - 1 year ago 97
Javascript Question

replace OR prepend values through jquery

I have a string value in a variable var string which can be

var string = '$ <input id='text'>';


var string = <input id='text'>;

I need to replace anything before
whether it may be
or any word. And if nothing is present need to prepend with the new value which is in
var newValue

I've tried it as follows but it works fine only if something is present before the input tag.

function replaceValue(newVal) {
amount.html(amount.html().replace(/[^\s]+/, newVal));

Is there any way I can prepend the value if nothing is present before input tag and restrict anyhow that
should not be replaced?

Answer Source

Cut off everything before the input and prepend the string you want to replace with.

To fix your code, you'd do:

function replaceValue(newVal) {
  amount.html(newVal + amount.html().slice(amount.html().indexOf('<input')));

and a runnable example without jQuery can be found here: https://jsfiddle.net/rffxbfhj/