Case insensitive String startsWith, contains, endsWith, replaceAll method
Claude Pache
claude.pache at gmail.com
Mon Feb 18 11:00:46 PST 2013
Le 18 févr. 2013 à 00:56, Biju <bijumaillist at gmail.com> a écrit :
> On 16 February 2013 20:26, David Bruant <bruant.d at gmail.com> wrote:
>> Le 17/02/2013 00:58, Biju a écrit :
>
>> Also, it doesn't seem that hard to implement:
>> String.prototype.startsWithI = function(s){
>> this.match(new RegExp('^'+s, 'i'));
>> }
>
> you also made the common error any developer make
> (I am ignoring you have missed the "return" keyword)
> If people at es-discuss can make error,
> how can you expect an average IT developer get it right.
>
> test this
>
> s="fddfd(ghgg"
> new RegExp('^'+s, 'i')
>
> Error!!!
>
Indeed (and I am surprised that David made such an error). The following implementation is more robust:
String.prototype.startsWithI = function(s) {
this.toLowerCase().startsWith(s.toLowerCase())
}
This approach will work for many, but not all, string functions.
>
>> And sometimes, case-sensitive is what you want.
> i agree, that is why I mentioned to add matchCase parameter.
> or have startsWithI, containsI, endsWithI instead
>
>>> Additionally we should have a String.replaceAll method right now web
>>> developers are using complex logic to achieve the same.
>>
>> "aA".replace(/a/ig, 'b'); // 'bb'
>> I feel the "i" and "g" flag or regexps aren't that complex. One just needs
>> to know about them.
>
> Again you are missing the point that the first parameter of "replace"
> at many times have to be a variable with a value which was taken from
> user input.
If there were a RegExp.escape function that escapes all characters in a string that have significance in a regular expression, you could write:
str.replace(new RegExp(RegExp.escape(searchString), 'ig'), replacement)
But sadly, such a function does not exist in EcmaScript, unless I missed it. Perhaps the following convenience function could be added:
RegExp.escape = function(string) {
return string.replace(/([(){}\[\].+*?|\\])/g, '\\$1')
}
(or: String.prototype.regExpEscape ?)
—Claude
>
>
> We you cant agree on replaceAll can we atleast bring mozilla
> non-standard flags parameter for String.replace as standard.
> https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/replace#Syntax
>
> You can see a lot of people asking for "replace all occurrences"
> https://www.google.com/search?q=javascript+replace+all+occurrences
>
> cheers
> Biju
> _______________________________________________
> es-discuss mailing list
> es-discuss at mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss
More information about the es-discuss
mailing list