0

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).

3
  • how about this jsfiddle.net/tq9et7bo/7 Commented Sep 14, 2015 at 5:00
  • You're probably looking for the built-in replace() function which takes a replacement function as a parameter. Commented Sep 14, 2015 at 5:02
  • Thanks MKA, Simon it worked for me. Commented Apr 22, 2016 at 19:21

3 Answers 3

1

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/

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

Comments

0

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"));

Comments

0

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)

Fiddle

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);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.