Remove string with javascript

How to remove part of a string?

Let’s say I have test_23 and I want to remove test_ . How do I do that? The prefix before _ can change.

7 Answers 7

My favourite way of doing this is «splitting and popping»:

var str = "test_23"; alert(str.split("_").pop()); // -> 23 var str2 = "adifferenttest_153"; alert(str2.split("_").pop()); // -> 153 

split() splits a string into an array of strings using a specified separator string.
pop() removes the last element from an array and returns that element.

The C programmer in me cringes at the number of objects created and destroyed on this simple split/pop operation 🙂 Probably: an array, 2 string, another array, another string.

You could add to your answer the possibility of using alert(str.split(«_»)[1]); since .split creates an array with two elements, [0] being before the «_» and [1] after. This was actually what I was looking for, but your answer helped me get there^^

@FernandoSilva Then, say if there were two «_» or more, we’d get 3 item array and be able to use/delete the third one too, right? BTW, +1. Exactly what I was looking for.

@TheLightSabrix take a look at it working, it’s much easier than trying to explain it in text. jsbin.com/keleguzacu/edit?js,console

If you want to remove part of string

let str = "try_me"; str.replace("try_", ""); // me 

If you want to replace part of string

let str = "try_me"; str.replace("try_", "test_"); // test_me 

Assuming your string always starts with ‘test_’ :

var str = 'test_23'; alert(str.substring('test_'.length)); 

use replace but that doesn’t work if there are multiple occurences. str.replace(«test_», «»); will return a new string where all occurences of «test_» are removed, so if only one occurence is guaranteed, then it should be fine. However, if there are multiple, I would use str = str.substring(0, str.indexOf(«test_)» + str.substring(str.indexOf(«test_») + 5, str.length); I know this is an old post but, if anyone comes across it, might help at least one person out there somewhere.

Источник

Remove string with javascript

Last updated: Jan 8, 2023
Reading time · 5 min

banner

# Table of Contents

# Remove a Substring from a String in JavaScript

Call the replace() method with the substring and an empty string to remove a substring from a string.

The replace() method will return a new string where the first occurrence of the given substring is removed.

Copied!
const str = 'one,one,two'; // ✅ Remove first occurrence of substring from string const removeFirst = str.replace('one', ''); console.log(removeFirst); // 👉️ ",one,two" // ✅ Remove all occurrences of substring from string const removeAll = str.replaceAll('one', ''); console.log(removeAll); // 👉️ ",,two"

remove substring from string

The String.replace() method returns a new string with one, some, or all matches of a regular expression replaced with the provided replacement.

Читайте также:  Javascript date только дата

The method takes the following parameters:

Name Description
pattern The pattern to look for in the string. Can be a string or a regular expression.
replacement A string used to replace the substring match by the supplied pattern.

We want to remove the substring, so we used an empty string as the replacement.

Copied!
const str = 'one,one,two'; // ✅ Remove first occurrence of substring from string const removeFirst = str.replace('one', ''); console.log(removeFirst); // 👉️ ",one,two"

The String.replace() method returns a new string with the matches of the pattern replaced. The method doesn’t change the original string.

Strings are immutable in JavaScript.

If you need to remove all occurrences of a substring from a string, use the String.replaceAll method.

# Remove all occurrences of a Substring from a String in JavaScript

Call the replaceAll() method with the substring and an empty string as parameters to remove all occurrences of a substring from a string.

The replaceAll method will return a new string where all occurrences of the substring are removed.

Copied!
const str = 'one,one,two'; const removeAll = str.replaceAll('one', ''); console.log(removeAll); // 👉️ ",,two"

remove all occurrences of substring from string

The String.replaceAll() method returns a new string with all matches of a pattern replaced by the provided replacement.

The method takes the following parameters:

Name Description
pattern The pattern to look for in the string. Can be a string or a regular expression.
replacement A string used to replace the substring match by the supplied pattern.

The code sample removes all occurrences of the substring from the string by replacing each occurrence with an empty string.

# Remove a substring from a string using a regular expression

Note that the replace and replaceAll methods can also be used with a regular expression.

If you don’t have a specific substring that you need to remove, but rather a pattern that you have to match, pass a regular expression as the first parameter to the replace method.

Copied!
const str = 'one,one,two'; // ✅ Remove first occurrence using regex const removeRegex = str.replace(/6/, ''); console.log(removeRegex); // 👉️ "23,one,two" // ✅ Remove all occurrences using regex const removeRegexAll = str.replace(/1/g, ''); console.log(removeRegexAll); // 👉️ ",one,two"

remove substring from string using regular expression

The forward slashes / / mark the beginning and end of the regular expression.

Inside the regular expression we have a character class [] that matches all digits in the range of 0 — 9 .

The first example only matches the first occurrence of a digit in the string and replaces it with an empty string.

If you ever need help reading a regular expression, check out this regular expression cheatsheet by MDN.

It contains a table with the name and the meaning of each special character with examples.

# Remove a substring from a string using String.slice()

You can also use the String.slice() method to remove a substring from a string.

Copied!
const str = 'one,two,three'; const newStr = str.slice(0, 3) + str.slice(7); console.log(newStr); // 👉️ one,three

remove substring from string using slice

The String.slice method extracts a section of a string and returns it, without modifying the original string.

The String.slice() method takes the following arguments:

Name Description
start index The index of the first character to include in the returned substring
end index The index of the first character to exclude from the returned substring
Читайте также:  Цикл ду вайл java

When only a single argument is passed to the String.slice() method, the slice goes to the end of the string.

The String.slice() method can be passed negative indexes to count backward.

Copied!
const str = 'bobbyhadz.com'; console.log(str.slice(-3)); // 👉️ com console.log(str.slice(-3, -1)); // 👉️ co console.log(str.slice(0, -1)); // 👉️ bobbyhadz.co

If you need to get the index of a substring in a string, use the String.indexOf() method.

Copied!
const str = 'one,two,three'; const substring = ',two'; const index = str.indexOf(substring); console.log(index); // 👉️ 3 const newString = str.slice(0, index) + str.slice(index + substring.length); console.log(newString); // 👉️ one,three

The String.indexOf method returns the index of the first occurrence of a substring in a string.

If the substring is not contained in the string, the method returns -1 .

You can use the String.lastIndexOf() method if you need to get the last index of a substring in a string.

Copied!
const str = 'one,two,three,two'; const substring = ',two'; const lastIndex = str.lastIndexOf(substring); console.log(lastIndex); // 👉️ 13

# Remove all occurrences of a Substring from a String using str.split()

This is a two-step process:

  1. Use the String.split() method to split the string on the substring.
  2. Use the Array.join() method to join the array without a separator.
Copied!
const str = 'one,one,two'; const result = str.split('one').join(''); console.log(result); // 👉️ ",,two"

remove all occurrences of substring from string using split

The String.split() method takes a separator and splits the string into an array on each occurrence of the provided delimiter.

The String.split() method takes the following 2 parameters:

Name Description
separator The pattern describing where each split should occur.
limit An integer used to specify a limit on the number of substrings to be included in the array.
Copied!
const str = 'one,one,two'; // 👇️ [ 'one', 'one', 'two' ] console.log(str.split(','));

The Array.join() method concatenates all of the elements in an array using a separator.

The only argument the Array.join() method takes is a separator — the string used to separate the elements of the array.

If the separator argument is set to an empty string, the array elements are joined without any characters in between them.

Copied!
const str = 'one,one,two'; const result = str.split('one').join(''); console.log(result); // 👉️ ",,two"

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

How to remove substring from string in javascript?

I have value of one variable is 03_ButtonAdd. I want to remove _ButtonAdd from it. means I want only numeric value. How to do it in javascript.?

3 Answers 3

'03_ButtonAdd'.replace('_ButtonAdd', ''); // returns: '03' 

Some more other methods would be:

s.substring(0,2); parseInt(s, 10) // returns `3`, not `'03'` /\d+/.exec(s)[0]; // Regex -> get all digits. 

And some more ugly / inefficient alternatives (Don’t use these):

s.split('_')[0]; // Split at _, get first index of array. var out = ''; for(var i = 0; i < s.length; i++)< if(isFinite(s[i]))< out += s[i]; >> // Seriously, now I'm just messing around, don't use this. 

Wait, a second ago you thought parseInt would return NaN . Suddenly it gets added to your answer. Seriously dude, if you just learned something new from someone else, don’t steal it from them.

Читайте также:  Configure php error logging

@epascarello: Okay, Regexes as small as this are maintainable, but if you get used to using them too much, you’ll end up using them for cases where they’re not required, making your code harder to understand. There. Changed the wording.

Also, @epascarello, while the difference is impossible to notice, parseInt seems to be twice as fast as using a regex. I think a downvote is hardly warranted for that reason, especially since the first part exactly answers the OP’s question to remove ‘_ButtonAdd’ from the string.

Источник

how to remove «,» from a string in javascript

original string is «a,d,k» I want to remove all , and make it to «adk» . I tried code below but it doesn’t work.

6 Answers 6

You aren’t assigning the result of the replace method back to your variable. When you call replace, it returns a new string without modifying the old one.

For example, load this into your favorite browser:

     

In this case, str1 will still be «a,d,k» and str2 will be «adk» .

If you want to change str1 , you should be doing:

var str1 = "a,d,k"; str1 = str1.replace (/,/g, ""); 

+1, but you can just do var str2; str2 = str.replace(. ). I’ve expanded on the answer to (hopefully) improve it.

var str = "a,d,k"; str = str.replace( /,/g, "" ); 

Note the g (global) flag on the regular expression, which matches all instances of «,».

If U want to delete more than one characters, say comma and dots you can write

  

You can try something like:

It’s more common answer. And can be use with s= document.location.href;

If you need a number greater than 999,999.00 you will have a problem.
These are only good for numbers less than 1 million, 1,000,000.
They only remove 1 or 2 commas.

Here the script that can remove up to 12 commas:

function uncomma(x) < var string1 = x; for (y = 0; y < 12; y++) < string1 = string1.replace(/\,/g, ''); >return string1; > 

Modify that for loop if you need bigger numbers.

The g in your regex means global and will remove all the commas from the string on the first pass the other 11 loops do nothing. Also you don’t need to escape the comma character in the literal. I would advise not being so hostile and critical of other people’s answers.

Also I was not being «hostile» or «critical». Just informing that the above example is flawed and does not work for numbers greater that 1 million. I needed the code, tested it, it failed, and I have posted my solution which worked only with 11 loops, did not work with 1. Can you tell me why that is? It goes against what you are saying. So I am unsure.

Источник

Оцените статью