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:45

No jQuery needed.

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.

查看更多
旧时光的记忆
3楼-- · 2019-01-02 17:45

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"

Demo

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

I was used to the C# (Sharp) String.Remove method. In Javascript, there is no remove function for string, but there is substr function. You can use the substr function once or twice to remove characters from string. You can make the following function to remove characters at start index to the end of string, just like the c# method first overload String.Remove(int startIndex):

function Remove(str, startIndex) {
    return str.substr(0, startIndex);
}

and/or you also can make the following function to remove characters at start index and count, just like the c# method second overload String.Remove(int startIndex, int count):

function Remove(str, startIndex, count) {
    return str.substr(0, startIndex) + str.substr(startIndex + count);
}

and then you can use these two functions or one of them for your needs!

Example:

alert(Remove("data-123", 0, 5));

Output: 123

查看更多
看淡一切
5楼-- · 2019-01-02 17:47

This little function I made has always worked for me :)

String.prototype.deleteWord = function (searchTerm) {
    var str = this;
    var n = str.search(searchTerm);
    while (str.search(searchTerm) > -1) {
        n = str.search(searchTerm);
        str = str.substring(0, n) + str.substring(n + searchTerm.length, str.length);
    }
    return str;
}

// Use it like this:
var string = "text is the the cool!!";
string.deleteWord('the'); // Returns text is cool!!

I know it is not the best, but It has always worked for me :)

查看更多
登录 后发表回答