952

I've got a data-123 string.

How can I remove data- from the string while leaving the 123?

Alexander Abakumov
  • 13,617
  • 16
  • 88
  • 129
Michael Grigsby
  • 11,467
  • 9
  • 33
  • 52

16 Answers16

1814

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.

Community
  • 1
  • 1
Evan Davis
  • 35,493
  • 6
  • 50
  • 57
  • How to replace multiple expressions? Do you have to use multiple .replace calls? – Dror Bar Feb 11 '20 at 16:20
  • 10
    For all occurrences to be discarded you can use `replaceAll` – Jeffery Tang Jul 22 '20 at 00:04
  • I tried to remove string using nodejs ```js const replace = "1." const replacer = new RegExp(replace, 'g', '') function removeText() { let originalText = ' 1. I can own unlimited wealth on this earth 2. My potential for wealth knows no bounds 3. I attract limitless financial opportunities '; let newText = originalText.replace(replacer, ''); console.log(newText); } removeText(); ``` using this code I can only remove "1." but what about `2.`, `3.`, I have this counting upto 100, can someone help me? – coco bar Jul 10 '23 at 13:04
181

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, "");
Meetai.com
  • 6,622
  • 3
  • 31
  • 38
James Johnson
  • 45,496
  • 8
  • 73
  • 110
  • Could you explain what the regex does? I dont get it why it replaces string except numbers if `0-9` was indicated. – rotimi-best May 14 '19 at 14:30
  • 2
    @rotimi-best `[^0-9\.]` means it will catch any letter that is *not* a digit or a period. notice the caret right after the first square bracket. – Michael T Dec 07 '20 at 10:44
81

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

laaposto
  • 11,835
  • 15
  • 54
  • 71
43

You can use slice(), if you will know in advance how many characters need slicing off the original string. It returns characters between a given start point to an end point.

string.slice(start, end);

Here are some examples showing how it works:

var mystr = ("data-123").slice(5); // This just defines a start point so the output is "123"
var mystr = ("data-123").slice(5,7); // This defines a start and an end  so the output is "12"

Demo

Mr. J
  • 1,524
  • 2
  • 19
  • 42
m.r shojaei
  • 447
  • 4
  • 5
32

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.

James Hill
  • 60,353
  • 20
  • 145
  • 161
22

1- If is the sequences into your string:

let myString = "mytest-text";
let myNewString = myString.replace("mytest-", "");

the answer is text

2- if you whant to remove the first 3 characters:

"mytest-text".substring(3);

the answer is est-text

17

Ex:-

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

Hopefully this will work for you.

Ajitej Kaushik
  • 932
  • 9
  • 30
Ranjit Kanojia
  • 171
  • 1
  • 2
16

Performance

Today 2021.01.14 I perform tests on MacOs HighSierra 10.13.6 on Chrome v87, Safari v13.1.2 and Firefox v84 for chosen solutions.

Results

For all browsers

  • solutions Ba, Cb, and Db are fast/fastest for long strings
  • solutions Ca, Da are fast/fastest for short strings
  • solutions Ab and E are slow for long strings
  • solutions Ba, Bb and F are slow for short strings

enter image description here

Details

I perform 2 tests cases:

  • short string - 10 chars - you can run it HERE
  • long string - 1 000 000 chars - you can run it HERE

Below snippet presents solutions Aa Ab Ba Bb Ca Cb Da Db E F

// https://stackoverflow.com/questions/10398931/how-to-strToRemove-text-from-a-string

// https://stackoverflow.com/a/10398941/860099
function Aa(str,strToRemove) {
  return str.replace(strToRemove,'');
}

// https://stackoverflow.com/a/63362111/860099
function Ab(str,strToRemove) {
  return str.replaceAll(strToRemove,'');
}

// https://stackoverflow.com/a/23539019/860099
function Ba(str,strToRemove) {
  let re = strToRemove.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // regexp escape char
  return str.replace(new RegExp(re),'');
}

// https://stackoverflow.com/a/63362111/860099
function Bb(str,strToRemove) {
  let re = strToRemove.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // regexp escape char
  return str.replaceAll(new RegExp(re,'g'),'');
}

// https://stackoverflow.com/a/27098801/860099
function Ca(str,strToRemove) {
  let start = str.indexOf(strToRemove);
  return str.slice(0,start) + str.slice(start+strToRemove.length, str.length);
}

// https://stackoverflow.com/a/27098801/860099
function Cb(str,strToRemove) {
  let start = str.search(strToRemove);
  return str.slice(0,start) + str.slice(start+strToRemove.length, str.length);
}

// https://stackoverflow.com/a/23181792/860099
function Da(str,strToRemove) {
  let start = str.indexOf(strToRemove);
  return str.substr(0, start) + str.substr(start + strToRemove.length);
}

// https://stackoverflow.com/a/23181792/860099
function Db(str,strToRemove) {
  let start = str.search(strToRemove);
  return str.substr(0, start) + str.substr(start + strToRemove.length);
}

// https://stackoverflow.com/a/49857431/860099
function E(str,strToRemove) {
  return str.split(strToRemove).join('');
}

// https://stackoverflow.com/a/45406624/860099
function F(str,strToRemove) {
    var n = str.search(strToRemove);
    while (str.search(strToRemove) > -1) {
        n = str.search(strToRemove);
        str = str.substring(0, n) + str.substring(n + strToRemove.length, str.length);
    }
    return str;
}


let str = "data-123";
let strToRemove = "data-";

[Aa,Ab,Ba,Bb,Ca,Cb,Da,Db,E,F].map( f=> console.log(`${f.name.padEnd(2,' ')} ${f(str,strToRemove)}`));
This shippet only presents functions used in performance tests - it not perform tests itself!

And here are example results for chrome

enter image description here

Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
13

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 cool!!";
string.deleteWord('the'); // Returns text is cool!!

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

HoldOffHunger
  • 18,769
  • 10
  • 104
  • 133
  • 1
    You are showing in your answer how replace function of string works more or less, but indeed just using the replace function of string is much more simpler and easier code then yours! –  Sep 02 '17 at 19:55
  • New to JavaScript but this was the only solution that worked for me. I disagree with the above comment because this is a while loop and not the same as a simple replace. – Kevin Moore Mar 25 '21 at 19:10
13
str.split('Yes').join('No'); 

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

ARC
  • 1,061
  • 14
  • 33
12

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

10

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.
Brett DeWoody
  • 59,771
  • 29
  • 135
  • 184
5

Update 2023

There are many ways to solve this problem, but I believe this is the simplest:

const newString = string.split("data-").pop();
console.log(newString); /// 123
S. Hesam
  • 5,266
  • 3
  • 37
  • 59
4

For doing such a thing there are a lot of different ways. A further way could be the following:

let str = 'data-123';
str = str.split('-')[1];
console.log('The remaining string is:\n' + str);

Basically the above code splits the string at the '-' char into two array elements and gets the second one, that is the one with the index 1, ignoring the first array element at the 0 index.

The following is one liner version:

console.log('The remaining string is:\n' + 'data-123'.split('-')[1]);

Another possible approach would be to add a method to the String prototype as follows:

String.prototype.remove = function (s){return this.replace(s,'')}

// After that it will be used like this:

a = 'ktkhkiksk kiksk ktkhkek kcklkekaknk kmkekskskakgkekk';
a = a.remove('k');
console.log(a);

Notice the above snippet will allow to remove only the first instance of the string you are interested to remove. But you can improve it a bit as follows:

String.prototype.removeAll = function (s){return this.replaceAll(s,'')}

// After that it will be used like this:

a = 'ktkhkiksk kiksk ktkhkek kcklkekaknk kmkekskskakgkekk';
a = a.removeAll('k');
console.log(a);

The above snippet instead will remove all instances of the string passed to the method. Of course you don't need to implement the functions into the prototype of the String object: you can implement them as simple functions too if you wish (I will show the remove all function, for the other you will need to use just replace instead of replaceAll, so it is trivial to implement):

function strRemoveAll(s,r)
{
    return s.replaceAll(r,'');
}

// you can use it as:

let a = 'ktkhkiksk kiksk ktkhkek kcklkekaknk kmkekskskakgkekk'
b = strRemoveAll (a,'k');
console.log(b);

Of course much more is possible.

willy wonka
  • 1,440
  • 1
  • 18
  • 31
1

Another way to replace all instances of a string is to use the new (as of August 2020) String.prototype.replaceAll() method.

It accepts either a string or RegEx as its first argument, and replaces all matches found with its second parameter, either a string or a function to generate the string.

As far as support goes, at time of writing, this method has adoption in current versions of all major desktop browsers* (even Opera!), except IE. For mobile, iOS SafariiOS 13.7+, Android Chromev85+, and Android Firefoxv79+ are all supported as well.

* This includes Edge/ Chrome v85+, Firefox v77+, Safari 13.1+, and Opera v71+

It'll take time for users to update to supported browser versions, but now that there's wide browser support, time is the only obstacle.

References:

You can test your current browser in the snippet below:

//Example coutesy of MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll
const p = 'The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?';

const regex = /dog/gi;

try {
  console.log(p.replaceAll(regex, 'ferret'));
  // expected output: "The quick brown fox jumps over the lazy ferret. If the ferret reacted, was it really lazy?"

  console.log(p.replaceAll('dog', 'monkey'));
  // expected output: "The quick brown fox jumps over the lazy monkey. If the monkey reacted, was it really lazy?"
  console.log('Your browser is supported!');
} catch (e) {
  console.log('Your browser is unsupported! :(');
}
.as-console-wrapper: {
  max-height: 100% !important;
}
zcoop98
  • 2,590
  • 1
  • 18
  • 31
1

Make sure that if you are replacing strings in a loop that you initiate a new Regex in each iteration. As of 9/21/21, this is still a known issue with Regex essentially missing every other match. This threw me for a loop when I encountered this the first time:

yourArray.forEach((string) => {
    string.replace(new RegExp(__your_regex__), '___desired_replacement_value___');
})

If you try and do it like so, don't be surprised if only every other one works

let reg = new RegExp('your regex');
yourArray.forEach((string) => {
    string.replace(reg, '___desired_replacement_value___');
})
Willie
  • 281
  • 3
  • 21