I've got a string that has data-123
as its value. How in jQuery
or Javascript
would I go in and remove the data-
from the string while leaving the 123
?
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- How to fix IE ClearType + jQuery opacity problem i
- void before promise syntax
- jQuery add and remove delay
This doesn't have anything to do with jQuery. You can use the JavaScript
replace
function for this:You can also pass a regex to this function. In the following example, it would replace everything except numerics:
Ex:-
Hopefully this will work for you.
Plain old JavaScript will suffice - jQuery is not necessary for such a simple task:
See:
.replace()
docs on MDN for additional information and usage.You can use
"data-123".replace('data-','');
, as mentioned, but asreplace()
only replaces the FIRST instance of the matching text, if your string was something like"data-123data-"
thenwill 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:And your output will be
"123"
DEMO2
This will replace all the occurrences of that specific string from original string.
Using
match()
andNumber()
to return anumber
variable:Here's what the statement above does...working middle-out:
str.match(/\d+$/)
- returns an array containing matches to any length of numbers at the end ofstr
. In this case it returns an array containing a single string item['123']
.Number()
- converts it to a number type. Because the array returned from.match()
contains a single elementNumber()
will return the number.