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
you can use js replace() function:
http://www.w3schools.com/jsref/jsref_replace.asp
so:
test.replace("ALL,", "");
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
.
if (part !== "ALL")
===
) 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.
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. :)
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","");
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.