you can use . indexOf() and . lastIndexOf() to determine if an index is repeated. Meaning, if the first occurrence of the character is also the last occurrence, then you know it doesn't repeat.
As an aside, when you are comparing Strings, you should use . equals() instead of == . Show activity on this post. I.e. if the number of distinct characters in the string is not the same as the total number of characters, you know there's a duplicate.
Answer: Use the indexOf() Method You can use the indexOf() method in conjugation with the push() remove the duplicate values from an array or get all unique values from an array in JavaScript.
Use this:
if(typeof(String.prototype.trim) === "undefined")
{
String.prototype.trim = function()
{
return String(this).replace(/^\s+|\s+$/g, '');
};
}
The trim function will now be available as a first-class function on your strings. For example:
" dog".trim() === "dog" //true
EDIT: Took J-P's suggestion to combine the regex patterns into one. Also added the global modifier per Christoph's suggestion.
Took Matthew Crumley's idea about sniffing on the trim function prior to recreating it. This is done in case the version of JavaScript used on the client is more recent and therefore has its own, native trim function.
For jquery users, how about $.trim(s)
Gumbo already noted this in a comment, but this bears repeating as an answer: the trim()
method was added in JavaScript 1.8.1 and is supported by all modern browsers (Firefox 3.5+, IE 9, Chrome 10, Safari 5.x), although IE 8 and older do not support it. Usage is simple:
" foo\n\t ".trim() => "foo"
See also:
Here's the function I use.
function trim(s){
return ( s || '' ).replace( /^\s+|\s+$/g, '' );
}
A better polyfill from the MDN that supports removal of BOM and NBSP:
if (!String.prototype.trim) {
String.prototype.trim = function () {
return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
};
}
Bear in mind that modifying built-in prototypes comes with a performance hit (due to the JS engine bailing on a number of runtime optimizations), and in performance critical situations you may need to consider the alternative of defining myTrimFunction(string)
instead. That being said, if you are targeting an older environment without native .trim()
support, you are likely to have more important performance issues to deal with.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With