How can I achieve the following using JQuery.
string = 'This $ should be greater than $ always'
.
in my case the above string also a variable, any replace function to replace $
with different variables, say
replace(string, var1, var2)
.
How can I achieve the following using JQuery.
string = 'This $ should be greater than $ always'
.
in my case the above string also a variable, any replace function to replace $
with different variables, say
replace(string, var1, var2)
.
Replace $ sign with another character try this:.
var s = "This is a string $ that contains $, a special character.";
s = s.replace(/\$/g, '*'); // use character instead of * according to you requirement.
I hope it will work. Here is the exmaple :-http://phpidiots.in/jquery/replace-special-character-with-another-character-using-jquery/
reinventing the wheel is not necessary here i guess but there is a jQuery plugin here jQuery.validator.format()
var template = jQuery.validator.format("{0} is not a valid value");
// later, results in 'abc is not a valid value'
alert(template("abc"));
From what I understood, I believe you want to replace $
with different values. For example, if var1 is val1
and var2 is val2
your original string This $ should be greater than $ always
once replaced should look like This val1 should be greater than val2 always
Provided that the number of $
symbols in your string is always equal to the number of values to be replaced, here is a solution. Note that I am using an array to hold the variable values.
credit to @Alnitak for the replaceAt function (refer to this SO thread)
var string = 'This $ should be greater than $ always';
arr = ["val1", "val2"];
$.each(arr, function(k,v){
string = replaceAt(string,string.indexOf('$'), v);
});
$('#display').html(string);
// replace the 'n'th character of 's' with 't'
function replaceAt(s, n, t) {
return s.substring(0, n) + t + s.substring(n + 1);
}