How to remove text from a string in JavaScript?

2019-01-02 16:51发布

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?

10条回答
闭嘴吧你
2楼-- · 2019-01-02 17:24

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, "");
查看更多
人间绝色
3楼-- · 2019-01-02 17:25

Ex:-

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

Hopefully this will work for you.

查看更多
几人难应
4楼-- · 2019-01-02 17:29

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.

查看更多
后来的你喜欢了谁
5楼-- · 2019-01-02 17:32

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

查看更多
低头抚发
6楼-- · 2019-01-02 17:41
str.split('Yes').join('No'); 

This will replace all the occurrences of that specific string from original string.

查看更多
栀子花@的思念
7楼-- · 2019-01-02 17:42

Using match() and Number() to return a number variable:

Number(("data-123").match(/\d+$/));

// strNum = 123

Here's what the statement above does...working middle-out:

  1. str.match(/\d+$/) - returns an array containing matches to any length of numbers at the end of str. In this case it returns an array containing a single string item ['123'].
  2. Number() - converts it to a number type. Because the array returned from .match() contains a single element Number() will return the number.
查看更多
登录 后发表回答