Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove string from a string jquery

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/

like image 504
Okky Avatar asked Apr 15 '13 07:04

Okky


People also ask

How to remove a character from a string in jQuery?

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.

How to remove text from a string in JavaScript?

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.

How to remove the string on button click using jQuery?

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.

How to replace the text of an empty string using jQuery?

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


3 Answers

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,'');
like image 57
halex Avatar answered Oct 11 '22 11:10

halex


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

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

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

like image 29
Jace Avatar answered Oct 11 '22 12:10

Jace


Try this

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

Demo

like image 45
Amit Avatar answered Oct 11 '22 10:10

Amit