21

I am trying to replace within a string using jquery

var myString ="qwerty"

var avoid ="t"

I want to do someting like

myString.replace(avoid,'');

I was able to remove like myString.replace('t',''); But i want it to be like myString.replace(avoid,'');

How to do it?

JsFiddle : http://jsfiddle.net/nKSZT/

7
  • 1
    Have you tried running this code? Commented Apr 15, 2013 at 7:43
  • Yes no error. But its not getting replaced Commented Apr 15, 2013 at 7:44
  • I have tried running it Commented Apr 15, 2013 at 7:45
  • 3
    You should store the replaced value, replace doesn't change the myString variable's value. Commented Apr 15, 2013 at 7:46
  • @undefined: You are right man. Sorry my mistake It worked. jsfiddle.net/nKSZT/1 Commented Apr 15, 2013 at 7:47

5 Answers 5

27

Your problem is that replace does not replace the characters in your original string but returns a new string with the replacement.

myString = myString.replace(avoid,'');
Sign up to request clarification or add additional context in comments.

Comments

10

replace does not modify the string, it returns a modified string. So do:

 var avoided = myString.replace(avoid,'');

Fiddle:
http://jsfiddle.net/MBjy3/1/

Comments

4

Try this

 var myString = "qwerty";
 alert(myString);
 var avoid = "t";
 var abc=myString.replace(avoid, '');
 alert(abc);

Demo

Comments

3
var str = "send_more_id4";
alert(str);
var res = str.replace("send_more_id", ""); 
alert(res);

Comments

2

Also, there is another approach:

var myString ="qwerty",
    avoid = "t";

var result = myString.split(avoid).join('');

console.log(result);

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.