jitendrapurohit jitendrapurohit - 1 month ago 11
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'>';


OR

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


I need to replace anything before
<input...
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
<input...
should not be replaced?

Answer

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/