1

I have a string like

 var test="ALL,l,1,2,3";

How to remove ALL from string if it contains using javascript.

Regards,

Raj

5 Answers 5

2

you can use js replace() function:

http://www.w3schools.com/jsref/jsref_replace.asp

so:

test.replace("ALL,", "");
1
  • how about providing an example? It wouldn't take long and make your answer much more useful. Commented Mar 14, 2011 at 15:38
1

If the word All can appear anywhere or more than once (e.g. "l,1,ALL,2,3,ALL") then have such code:

var test = "l,1,ALL,2,3,ALL"
var parts = test.split(",");
var clean = [];
for (var i = 0; i < parts.length; i++) {
   var part = parts[i];
   if (part !== "ALL")
      clean.push(part);
}
var newTest = clean.join(",");

After this the variable newTest will hold the string without ALL.

4
  • Use strict equality. if (part !== "ALL") Commented Mar 14, 2011 at 16:05
  • @Matt what are the advantages of this, if I may ask? Commented Mar 14, 2011 at 16:08
  • The strict equality operator (===) does not perform type coercion if the operand types are different, is generally "good practice", and is a teeny bit faster. See [this question]( stackoverflow.com/questions/359494) for more. Commented Mar 14, 2011 at 16:32
  • 1
    @Matt cheers, I'm convinced. For those reading the comments, the most simple example is alert(5 == "5") vs. alert(5 === "5") - the first returns true as the type doesn't matter so JS is converting types by itself while the second will show false as the values are of different types. In this case split() returns array of strings so the type is guaranteed to be the same. :) Commented Mar 15, 2011 at 8:08
0

If all you want to do is remove occurrences of the string "ALL" from another string, you can use the JavaScript String object's replace method:

test.replace("ALL","");
0

I'm not really sure if you want to remove all instances of capital letters from your string, but you are probably looking at using a regular expression such as s.replace(/[A-Z]/g,"") where s is the string.
Looking up javascript RegExp will give more indepth details.

0

use:

test.replace ( 'ALL,',  '' ); 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.