How to remove text from a string in JavaScript?

How to remove text from a string in JavaScript?

I’ve got a string that has data-123 as its value. How would I go in and remove data- from the string while leaving the 123 in jQuery or JavaScript?


Solution 1:

No jQuery needed.

var ret = "data-123".replace('data-','');
console.log(ret);   //prints: 123


For all occurrences to be discarded use:

var ret = "data-123".replace(/data-/g,'');

PS: The replace function returns a new string and leaves the original string unchanged, so use the function return value after the replace() call.

Solution 2:

This doesn’t have anything to do with jQuery. You can use the JavaScript replace function for this:

var str = "data-123";
str = str.replace("data-", "");

You can also pass a regex to this function. In the following example, it would replace everything except numerics:

str = str.replace(/[^0-9\.]+/g, "");

Solution 3:

You can use "data-123".replace('data-','');, as mentioned, but as replace() only replaces the FIRST instance of the matching text, if your string was something like "data-123data-" then


will only replace the first matching text. And your output will be "123data-"


So if you want all matches of text to be replaced in string you have to use a regular expression with the g flag like that:


And your output will be "123"


Solution 4:

you can use slice() it returens charcters between start to end (included end point)

   string.slice(start , end);

here is some exmp to show how it works:

var mystr = ("data-123").slice(5); // jast define start point so output is "123"
var mystr = ("data-123").slice(5,7); // define start and end  so output is "12"
var mystr=(",246").slice(1); // returens "246"


Solution 5:

Plain old JavaScript will suffice – jQuery is not necessary for such a simple task:

var myString = "data-123";
var myNewString = myString.replace("data-", "");

See: .replace() docs on MDN for additional information and usage.

Solution 6:


var value="Data-123";
var removeData=value.replace("Data-","");

Hopefully this will work for you.