How to remove text from a string?
I've got a data-123
string.
How can I remove data-
from the string while leaving the 123
?
Solution 1:
var ret = "data-123".replace('data-','');
console.log(ret); //prints: 123
Docs.
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
"data-123data-".replace('data-','');
will only replace the first matching text. And your output will be "123data-"
DEMO
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:
"data-123data-".replace(/data-/g,'');
And your output will be "123"
DEMO2