2

I am doing the following thing to replace some part of the string. I want to replace all three occurence of the string but it is not working.

 var  hdnval = document.getElementById("hdnColgval").value = response;
$("#ddcolgs").val($("#ddcolgs").val().replace(/'+hdnval+'/g, response));
1
  • 1
    If you like jQuery, you'd love Vanilla JS Commented Dec 11, 2012 at 8:55

5 Answers 5

1

You are trying to append a string to a regex which will cause errors. If you are simply replacing strings, try this:

var hdnval = document.getElementById("hdnColgval").value = response;
$("#ddcolgs").val($("#ddcolgs").val().replace(hdnval, response));

If the value of #hdnColgval is supposed to be a regex expression, use this:

var hdnval = document.getElementById("hdnColgval").value = response;
var regex = new Regex(hdnval, 'g');
$("#ddcolgs").val($("#ddcolgs").val().replace(regex, response));
Sign up to request clarification or add additional context in comments.

2 Comments

hi Rory McCrossan thxs 4 u answer it really helped.........One more question......I have a string '|lcol~-1|lcol~-1' now i need to find wether the string contains '-1' using javascript
@vidyasagar85 you can use test(), like this: '|lcol~-1|lcol~-1'.test('-1') which will return true/false depending on whether -1 was found.
0

You can't create a regular expression from a variable in that way.. try:

.replace(new RegExp(hdnval, 'g'), response);

Comments

0

To use your variable in the regex, use the new Regexp method:

var  hdnval = document.getElementById("hdnColgval").value,
         re = new RegExp(hdnval, "g");

$("#ddcolgs").val(function(i,v) {
   return v.replace(re, response);
});

Comments

0

Your implementation is almost correct, jssut remove the quotes. You don't need them

var  hdnval = document.getElementById("hdnColgval").value = response;
$("#ddcolgs").val($("#ddcolgs").val().replace(/hdnval/g, response));

Comments

0
$("#ddcolgs").val(function(i, val) {
    return val.replace(RegExp(hdnval,'g'), response);
}

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.