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/
To perform this task, you have to use the jQuery text () to get the string characters. Use a variable where you want to get the string characters. Now, suppose you want to remove the character named ‘s’ from the string.
You can remove text from a string in Javascript using 2 methods, substring and replace. JS string class provides a substring method that can be used to extract a substring from a given string. This can be used to remove text from either or both ends of the string.
You need to use the click event of jQuery to remove the string on button click. To perform this task, you have to use the jQuery text () to get the string characters. Use a variable where you want to get the string characters.
Of course, you can use this same method to replace any text for an empty string removing the searched string from our text. We can replace the whole text of any element on our page by using the text function of jQuery. It's even more simple yet: $("#element").text("What's up!");
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,'');
replace
does not modify the string, it returns a modified string. So do:
var avoided = myString.replace(avoid,'');
Fiddle:
http://jsfiddle.net/MBjy3/1/
Try this
var myString = "qwerty";
alert(myString);
var avoid = "t";
var abc=myString.replace(avoid, '');
alert(abc);
Demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With