Regular expression length - javascript

What do you think about using looooooong regular expressions? Does this affect performance?
This is one of my regular expressions: (blockquote messed it up, so I edited it)
([(]((((-?((([0-9]+)|([(]-[0-9]+[)]))|(([0-9]*i)|([(]-[0-9]*i[)])))[*/]((([0-9]*i)|([(]-[0-9]*i[)]))|(([0-9]+)|([(]-[0-9]+[)]))))|(-?(([0-9]+)|([(]-[0-9]+[)]))[+-](([0-9]*i)|([(]-[0-9]*i[)]))[+-]((([0-9]*i)|([(]-[0-9]*i[)]))|(([0-9]+)|([(]-[0-9]+[)]))))|([(]((-?(([0-9]+)|([(]-[0-9]+[)]))[+-](([0-9]*i)|([(]-[0-9]*i[)])))|(-?(([0-9]*i)|([(]-[0-9]*i[)]))[+-](([0-9]+)|([(]-[0-9]+[)]))))[)][+/*-]([(]((-?(([0-9]+)|([(]-[0-9]+[)]))[+-](([0-9]*i)|([(]-[0-9]*i[)])))|(-?(([0-9]*i)|([(]-[0-9]*i[)]))[+-](([0-9]+)|([(]-[0-9]+[)]))))[)]|(([0-9]*i)|([(]-[0-9]*i[)]))|(([0-9]+)|([(]-[0-9]+[)]))))|(-?(([0-9]*i)|([(]-[0-9]*i[)]))[+/*-]((([0-9]*i)|([(]-[0-9]*i[)]))|[(]((-?(([0-9]+)|([(]-[0-9]+[)]))[+-](([0-9]*i)|([(]-[0-9]*i[)])))|(-?(([0-9]*i)|([(]-[0-9]*i[)]))[+-](([0-9]+)|([(]-[0-9]+[)]))))[)]))|(-?(([0-9]+)|([(]-[0-9]+[)]))[+/*-]((([0-9]+)|([(]-[0-9]+[)]))|[(]((-?(([0-9]+)|([(]-[0-9]+[)]))[+-](([0-9]*i)|([(]-[0-9]*i[)])))|(-?(([0-9]*i)|([(]-[0-9]*i[)]))[+-](([0-9]+)|([(]-[0-9]+[)]))))[)])))([+/*-](((-?((([0-9]+)|([(]-[0-9]+[)]))|(([0-9]*i)|([(]-[0-9]*i[)])))[*/]((([0-9]*i)|([(]-[0-9]*i[)]))|(([0-9]+)|([(]-[0-9]+[)]))))|(-?(([0-9]+)|([(]-[0-9]+[)]))[+-](([0-9]*i)|([(]-[0-9]*i[)]))[+-]((([0-9]*i)|([(]-[0-9]*i[)]))|(([0-9]+)|([(]-[0-9]+[)]))))|([(]((-?(([0-9]+)|([(]-[0-9]+[)]))[+-](([0-9]*i)|([(]-[0-9]*i[)])))|(-?(([0-9]*i)|([(]-[0-9]*i[)]))[+-](([0-9]+)|([(]-[0-9]+[)]))))[)][+/*-]([(]((-?(([0-9]+)|([(]-[0-9]+[)]))[+-](([0-9]*i)|([(]-[0-9]*i[)])))|(-?(([0-9]*i)|([(]-[0-9]*i[)]))[+-](([0-9]+)|([(]-[0-9]+[)]))))[)]|(([0-9]*i)|([(]-[0-9]*i[)]))|(([0-9]+)|([(]-[0-9]+[)]))))|(-?(([0-9]*i)|([(]-[0-9]*i[)]))[+/*-]((([0-9]*i)|([(]-[0-9]*i[)]))|[(]((-?(([0-9]+)|([(]-[0-9]+[)]))[+-](([0-9]*i)|([(]-[0-9]*i[)])))|(-?(([0-9]*i)|([(]-[0-9]*i[)]))[+-](([0-9]+)|([(]-[0-9]+[)]))))[)]))|(-?(([0-9]+)|([(]-[0-9]+[)]))[+/*-]((([0-9]+)|([(]-[0-9]+[)]))|[(]((-?(([0-9]+)|([(]-[0-9]+[)]))[+-](([0-9]*i)|([(]-[0-9]*i[)])))|(-?(([0-9]*i)|([(]-[0-9]*i[)]))[+-](([0-9]+)|([(]-[0-9]+[)]))))[)])))|(([0-9]*i)|([(]-[0-9]*i[)]))|(([0-9]+)|([(]-[0-9]+[)]))|[(]((-?(([0-9]+)|([(]-[0-9]+[)]))[+-](([0-9]*i)|([(]-[0-9]*i[)])))|(-?(([0-9]*i)|([(]-[0-9]*i[)]))[+-](([0-9]+)|([(]-[0-9]+[)]))))[)]))*)|(((([0-9]*i)|([(]-[0-9]*i[)]))|(([0-9]+)|([(]-[0-9]+[)]))|[(]((-?(([0-9]+)|([(]-[0-9]+[)]))[+-](([0-9]*i)|([(]-[0-9]*i[)])))|(-?(([0-9]*i)|([(]-[0-9]*i[)]))[+-](([0-9]+)|([(]-[0-9]+[)]))))[)])([+/*-]((-?((([0-9]+)|([(]-[0-9]+[)]))|(([0-9]*i)|([(]-[0-9]*i[)])))[*/]((([0-9]*i)|([(]-[0-9]*i[)]))|(([0-9]+)|([(]-[0-9]+[)]))))|(-?(([0-9]+)|([(]-[0-9]+[)]))[+-](([0-9]*i)|([(]-[0-9]*i[)]))[+-]((([0-9]*i)|([(]-[0-9]*i[)]))|(([0-9]+)|([(]-[0-9]+[)]))))|([(]((-?(([0-9]+)|([(]-[0-9]+[)]))[+-](([0-9]*i)|([(]-[0-9]*i[)])))|(-?(([0-9]*i)|([(]-[0-9]*i[)]))[+-](([0-9]+)|([(]-[0-9]+[)]))))[)][+/*-]([(]((-?(([0-9]+)|([(]-[0-9]+[)]))[+-](([0-9]*i)|([(]-[0-9]*i[)])))|(-?(([0-9]*i)|([(]-[0-9]*i[)]))[+-](([0-9]+)|([(]-[0-9]+[)]))))[)]|(([0-9]*i)|([(]-[0-9]*i[)]))|(([0-9]+)|([(]-[0-9]+[)]))))|(-?(([0-9]*i)|([(]-[0-9]*i[)]))[+/*-]((([0-9]*i)|([(]-[0-9]*i[)]))|[(]((-?(([0-9]+)|([(]-[0-9]+[)]))[+-](([0-9]*i)|([(]-[0-9]*i[)])))|(-?(([0-9]*i)|([(]-[0-9]*i[)]))[+-](([0-9]+)|([(]-[0-9]+[)]))))[)]))|(-?(([0-9]+)|([(]-[0-9]+[)]))[+/*-]((([0-9]+)|([(]-[0-9]+[)]))|[(]((-?(([0-9]+)|([(]-[0-9]+[)]))[+-](([0-9]*i)|([(]-[0-9]*i[)])))|(-?(([0-9]*i)|([(]-[0-9]*i[)]))[+-](([0-9]+)|([(]-[0-9]+[)]))))[)]))))+))[)])
Can i use RegExp this length or is it bad practise?
EDIT
I'm constructing complex number calculator. This regex is made from shorter ones. This is how i am doing it:
var regularExpression = new (function()
{
this.re = "(([0-9]+)|([(]-[0-9]+[)]))",
this.im = "(([0-9]*i)|([(]-[0-9]*i[)]))",
this.complexNumber = "[(]((-?"+ this.re + "[+-]" + this.im + ")|(-?" + this.im + "[+-]" + this.re +"))[)]",
this.expression = "("+
"(-?("+this.re+"|"+this.im+")[*/]("+this.im+"|"+this.re+"))|"+
"(-?"+this.re+"[+-]"+this.im+"[+-]("+this.im+"|"+this.re+"))|"+
"("+this.complexNumber+"[+/*-]("+this.complexNumber+"|"+this.im+"|"+this.re+"))|"+
"(-?"+this.im+"[+/*-](" + this.im+"|"+this.complexNumber+"))|"+
"(-?"+this.re+"[+/*-](" + this.re+"|"+this.complexNumber+"))"+
")",
this.simpleExpression = "([(]("+
"("+this.expression+"([+/*-]("+this.expression+"|"+this.im+"|"+this.re+"|"+this.complexNumber+"))*)|"+
"(("+this.im+"|"+this.re+"|"+this.complexNumber+")([+/*-]"+this.expression+")+)"+
")[)])"
})();
So my regularExpression.simpleExpression is even longer, because is uses expression few times. Thats why I'm asking and worried.
simpleExpression is looking for strings like: (12321-12231i+1233123*(12i-231)+12323-i)

Regular expressions are very fast, when they are written in a good manner (definitely much faster than e.g. the code based on conditionals).
However, the question you should ask yourself is whether the code is maintainable and readable - someone may have to rewrite this part of the code in the future and even you might not understand it at first glance after some time.
First point from here might answer your question: https://hackernoon.com/few-simple-rules-for-good-coding-my-15-years-experience-96cb29d4acd9

Related

Capitalise first letter in the one line code [duplicate]

How do I make the first character of a string uppercase if it's a letter, but not change the case of any of the other letters?
For example:
"this is a test" → "This is a test"
"the Eiffel Tower" → "The Eiffel Tower"
"/index.html" → "/index.html"
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
Some other answers modify String.prototype (this answer used to as well), but I would advise against this now due to maintainability (hard to find out where the function is being added to the prototype and could cause conflicts if other code uses the same name/a browser adds a native function with that same name in future).
Edited to add this DISCLAIMER: please read the comments to understand the risks of editing JS basic types.
Here's a more object-oriented approach:
Object.defineProperty(String.prototype, 'capitalize', {
value: function() {
return this.charAt(0).toUpperCase() + this.slice(1);
},
enumerable: false
});
You'd call the function, like this:
"hello, world!".capitalize();
With the expected output being:
"Hello, world!"
In CSS:
p::first-letter {
text-transform:capitalize;
}
Here is a shortened version of the popular answer that gets the first letter by treating the string as an array:
function capitalize(s)
{
return s[0].toUpperCase() + s.slice(1);
}
Update
According to the comments below this doesn't work in IE 7 or below.
Update 2:
To avoid undefined for empty strings (see #njzk2's comment below), you can check for an empty string:
function capitalize(s)
{
return s && s[0].toUpperCase() + s.slice(1);
}
ES version
const capitalize = s => s && s[0].toUpperCase() + s.slice(1)
// to always return type string event when s may be falsy other than empty-string
const capitalize = s => (s && s[0].toUpperCase() + s.slice(1)) || ""
If you're interested in the performance of a few different methods posted:
Here are the fastest methods based on this jsperf test (ordered from fastest to slowest).
As you can see, the first two methods are essentially comparable in terms of performance, whereas altering the String.prototype is by far the slowest in terms of performance.
// 10,889,187 operations/sec
function capitalizeFirstLetter(string) {
return string[0].toUpperCase() + string.slice(1);
}
// 10,875,535 operations/sec
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
// 4,632,536 operations/sec
function capitalizeFirstLetter(string) {
return string.replace(/^./, string[0].toUpperCase());
}
// 1,977,828 operations/sec
String.prototype.capitalizeFirstLetter = function() {
return this.charAt(0).toUpperCase() + this.slice(1);
}
I didn’t see any mention in the existing answers of issues related to astral plane code points or internationalization. “Uppercase” doesn’t mean the same thing in every language using a given script.
Initially I didn’t see any answers addressing issues related to astral plane code points. There is one, but it’s a bit buried (like this one will be, I guess!)
Overview of the hidden problem and various approaches to it
Most of the proposed functions look like this:
function capitalizeFirstLetter(str) {
return str[0].toUpperCase() + str.slice(1);
}
However, some cased characters fall outside the BMP (basic multilingual plane, code points U+0 to U+FFFF). For example take this Deseret text:
capitalizeFirstLetter("𐐶𐐲𐑌𐐼𐐲𐑉"); // "𐐶𐐲𐑌𐐼𐐲𐑉"
The first character here fails to capitalize because the array-indexed properties of strings don’t access “characters” or code points*. They access UTF-16 code units. This is true also when slicing — the index values point at code units.
It happens to be that UTF-16 code units are 1:1 with USV code points within two ranges, U+0 to U+D7FF and U+E000 to U+FFFF inclusive. Most cased characters fall into those two ranges, but not all of them.
From ES2015 on, dealing with this became a bit easier. String.prototype[##iterator] yields strings corresponding to code points**. So for example, we can do this:
function capitalizeFirstLetter([ first='', ...rest ]) {
return [ first.toUpperCase(), ...rest ].join('');
}
capitalizeFirstLetter("𐐶𐐲𐑌𐐼𐐲𐑉") // "𐐎𐐲𐑌𐐼𐐲𐑉"
For longer strings, this is probably not terribly efficient*** — we don’t really need to iterate the remainder. We could use String.prototype.codePointAt to get at that first (possible) letter, but we’d still need to determine where the slice should begin. One way to avoid iterating the remainder would be to test whether the first codepoint is outside the BMP; if it isn’t, the slice begins at 1, and if it is, the slice begins at 2.
function capitalizeFirstLetter(str) {
if (!str) return '';
const firstCP = str.codePointAt(0);
const index = firstCP > 0xFFFF ? 2 : 1;
return String.fromCodePoint(firstCP).toUpperCase() + str.slice(index);
}
capitalizeFirstLetter("𐐶𐐲𐑌𐐼𐐲𐑉") // "𐐎𐐲𐑌𐐼𐐲𐑉"
You could use bitwise math instead of > 0xFFFF there, but it’s probably easier to understand this way and either would achieve the same thing.
We can also make this work in ES5 and below by taking that logic a bit further if necessary. There are no intrinsic methods in ES5 for working with codepoints, so we have to manually test whether the first code unit is a surrogate****:
function capitalizeFirstLetter(str) {
if (!str) return '';
var firstCodeUnit = str[0];
if (firstCodeUnit < '\uD800' || firstCodeUnit > '\uDFFF') {
return str[0].toUpperCase() + str.slice(1);
}
return str.slice(0, 2).toUpperCase() + str.slice(2);
}
capitalizeFirstLetter("𐐶𐐲𐑌𐐼𐐲𐑉") // "𐐎𐐲𐑌𐐼𐐲𐑉"
Deeper into internationalization (whose capitalization?)
At the start I also mentioned internationalization considerations. Some of these are very difficult to account for because they require knowledge not only of what language is being used, but also may require specific knowledge of the words in the language. For example, the Irish digraph "mb" capitalizes as "mB" at the start of a word. Another example, the German eszett, never begins a word (afaik), but still helps illustrate the problem. The lowercase eszett (“ß”) capitalizes to “SS,” but “SS” could lowercase to either “ß” or “ss” — you require out-of-band knowledge of the German language to know which is correct!
The most famous example of these kinds of issues, probably, is Turkish. In Turkish Latin, the capital form of i is İ, while the lowercase form of I is ı — they’re two different letters. Fortunately we do have a way to account for this:
function capitalizeFirstLetter([ first='', ...rest ], locale) {
return [ first.toLocaleUpperCase(locale), ...rest ].join('');
}
capitalizeFirstLetter("italy", "en") // "Italy"
capitalizeFirstLetter("italya", "tr") // "İtalya"
In a browser, the user’s most-preferred language tag is indicated by navigator.language, a list in order of preference is found at navigator.languages, and a given DOM element’s language can be obtained (usually) with Object(element.closest('[lang]')).lang || YOUR_DEFAULT_HERE in multilanguage documents.
In agents which support Unicode property character classes in RegExp, which were introduced in ES2018, we can clean stuff up further by directly expressing what characters we’re interested in:
function capitalizeFirstLetter(str, locale=navigator.language) {
return str.replace(/^\p{CWU}/u, char => char.toLocaleUpperCase(locale));
}
This could be tweaked a bit to also handle capitalizing multiple words in a string with fairly good accuracy for at least some languages, though outlying cases will be hard to avoid completely if doing so no matter what the primary language is.
The CWU or Changes_When_Uppercased character property matches all code points which change when uppercased in the generic case where specific locale data is absent. There are other interesting case-related Unicode character properties that you may wish to play around with. It’s a cool zone to explore but we’d go on all day if we enumerated em all here. Here’s something to get your curiosity going if you’re unfamiliar, though: \p{Lower} is a larger group than \p{LowercaseLetter} (aka \p{Ll}) — conveniently illustrated by the default character set comparison in this tool provided by Unicode. (NB: not everything you can reference there is also available in ES regular expressions, but most of the stuff you’re likely to want is).
Alternatives to case-mapping in JS (Firefox & CSS love the Dutch!)
If digraphs with unique locale/language/orthography capitalization rules happen to have a single-codepoint “composed” representation in Unicode, these might be used to make one’s capitalization expectations explicit even in the absence of locale data. For example, we could prefer the composed i-j digraph, ij / U+133, associated with Dutch, to ensure a case-mapping to uppercase IJ / U+132:
capitalizeFirstLetter('ijsselmeer'); // "IJsselmeer"
On the other hand, precomposed digraphs and similar are sometimes deprecated (like that one, it seems!) and may be undesirable in interchanged text regardless due to the potential copypaste nuisance if that’s not the normal way folks type the sequence in practice. Unfortunately, in the absence of the precomposition “hint,” an explicit locale won’t help here (at least as far as I know). If we spell ijsselmeer with an ordinary i + j, capitalizeFirstLetter will produce the wrong result even if we explicitly indicate nl as the locale:
capitalizeFirstLetter('ijsselmeer', 'nl'); // "Ijsselmeer" :(
(I’m not entirely sure whether there are some such cases where the behavior comes down to ICU data availability — perhaps someone else could say.)
If the point of the transformation is to display textual content in a web browser, though, you have an entirely different option available that will likely be your best bet: leveraging features of the web platform’s other core languages, HTML and CSS. Armed with HTML’s lang=... and CSS’s text-transform:..., you’ve got a (pseudo-)declarative solution that leaves extra room for the user agent to be “smart.” A JS API needs to have predictable outcomes across all browsers (generally) and isn’t free to experiment with heuristics. The user-agent itself is obligated only to its user, though, and heuristic solutions are fair game when the output is for a human being. If we tell it “this text is Dutch, but please display it capitalized,” the particular outcome might now vary between browsers, but it’s likely going to be the best each of them could do. Let’s see:
<!DOCTYPE html>
<dl>
<dt>Untransformed
<dd>ijsselmeer
<dt>Capitalized with CSS and <code>lang=en</code>
<dd lang="en" style="text-transform: capitalize">ijsselmeer
<dt>Capitalized with CSS and <code>lang=nl</code>
<dd lang="nl" style="text-transform: capitalize">ijsselmeer
In Chromium at the time of writing, both the English and Dutch lines come out as Ijsselmeer — so it does no better than JS. But try it in current Firefox! The element that we told the browser contains Dutch will be correctly rendered as IJsselmeer there.
This solution is purpose-specific (it’s not gonna help you in Node, anyway) but it was silly of me not to draw attention to it previously given some folks might not realize they’re googling the wrong question. Thanks #paul23 for clarifying more about the nature of the IJ digraph in practice and prompting further investigation!
As of January 2021, all major engines have implemented the Unicode property character class feature, but depending on your target support range you may not be able to use it safely yet. The last browser to introduce support was Firefox (78; June 30, 2020). You can check for support of this feature with the Kangax compat table. Babel can be used to compile RegExp literals with property references to equivalent patterns without them, but be aware that the resulting code can sometimes be enormous. You probably would not want to do this unless you’re certain the tradeoff is justified for your use case.
In all likelihood, people asking this question will not be concerned with Deseret capitalization or internationalization. But it’s good to be aware of these issues because there’s a good chance you’ll encounter them eventually even if they aren’t concerns presently. They’re not “edge” cases, or rather, they’re not by-definition edge cases — there’s a whole country where most people speak Turkish, anyway, and conflating code units with codepoints is a fairly common source of bugs (especially with regard to emoji). Both strings and language are pretty complicated!
* The code units of UTF-16 / UCS2 are also Unicode code points in the sense that e.g. U+D800 is technically a code point, but that’s not what it “means” here ... sort of ... though it gets pretty fuzzy. What the surrogates definitely are not, though, is USVs (Unicode scalar values).
** Though if a surrogate code unit is “orphaned” — i.e., not part of a logical pair — you could still get surrogates here, too.
*** maybe. I haven’t tested it. Unless you have determined capitalization is a meaningful bottleneck, I probably wouldn’t sweat it — choose whatever you believe is most clear and readable.
**** such a function might wish to test both the first and second code units instead of just the first, since it’s possible that the first unit is an orphaned surrogate. For example the input "\uD800x" would capitalize the X as-is, which may or may not be expected.
For another case I need it to capitalize the first letter and lowercase the rest. The following cases made me change this function:
//es5
function capitalize(string) {
return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();
}
capitalize("alfredo") // => "Alfredo"
capitalize("Alejandro")// => "Alejandro
capitalize("ALBERTO") // => "Alberto"
capitalize("ArMaNdO") // => "Armando"
// es6 using destructuring
const capitalize = ([first,...rest]) => first.toUpperCase() + rest.join('').toLowerCase();
This is the 2018 ECMAScript 6+ Solution:
const str = 'the Eiffel Tower';
const newStr = `${str[0].toUpperCase()}${str.slice(1)}`;
console.log('Original String:', str); // the Eiffel Tower
console.log('New String:', newStr); // The Eiffel Tower
If you're already (or considering) using Lodash, the solution is easy:
_.upperFirst('fred');
// => 'Fred'
_.upperFirst('FRED');
// => 'FRED'
_.capitalize('fred') //=> 'Fred'
See their documentation: https://lodash.com/docs#capitalize
_.camelCase('Foo Bar'); //=> 'fooBar'
https://lodash.com/docs/4.15.0#camelCase
_.lowerFirst('Fred');
// => 'fred'
_.lowerFirst('FRED');
// => 'fRED'
_.snakeCase('Foo Bar');
// => 'foo_bar'
Vanilla JavaScript for first upper case:
function upperCaseFirst(str){
return str.charAt(0).toUpperCase() + str.substring(1);
}
There is a very simple way to implement it by replace. For ECMAScript 6:
'foo'.replace(/^./, str => str.toUpperCase())
Result:
'Foo'
Capitalize the first letter of all words in a string:
function ucFirstAllWords( str )
{
var pieces = str.split(" ");
for ( var i = 0; i < pieces.length; i++ )
{
var j = pieces[i].charAt(0).toUpperCase();
pieces[i] = j + pieces[i].substr(1);
}
return pieces.join(" ");
}
CSS only
If the transformation is needed only for displaying on a web page:
p::first-letter {
text-transform: uppercase;
}
Despite being called "::first-letter", it applies to the first character, i.e. in case of string %a, this selector would apply to % and as such a would not be capitalized.
In IE9+ or IE5.5+ it's supported in legacy notation with only one colon (:first-letter).
ES2015 one-liner
const capitalizeFirstChar = str => str.charAt(0).toUpperCase() + str.substring(1);
Remarks
In the benchmark I performed, there was no significant difference between string.charAt(0) and string[0]. Note however, that string[0] would be undefined for an empty string, so the function would have to be rewritten to use "string && string[0]", which is way too verbose, compared to the alternative.
string.substring(1) is faster than string.slice(1).
Benchmark between substring() and slice()
The difference is rather minuscule nowadays (run the test yourself):
21,580,613.15 ops/s ±1.6% for substring(),
21,096,394.34 ops/s ±1.8% (2.24% slower) for slice().
It's always better to handle these kinds of stuff using CSS first, in general, if you can solve something using CSS, go for that first, then try JavaScript to solve your problems, so in this case try using :first-letter in CSS and apply text-transform:capitalize;
So try creating a class for that, so you can use it globally, for example: .first-letter-uppercase and add something like below in your CSS:
.first-letter-uppercase:first-letter {
text-transform:capitalize;
}
Also the alternative option is JavaScript, so the best gonna be something like this:
function capitalizeTxt(txt) {
return txt.charAt(0).toUpperCase() + txt.slice(1); //or if you want lowercase the rest txt.slice(1).toLowerCase();
}
and call it like:
capitalizeTxt('this is a test'); // return 'This is a test'
capitalizeTxt('the Eiffel Tower'); // return 'The Eiffel Tower'
capitalizeTxt('/index.html'); // return '/index.html'
capitalizeTxt('alireza'); // return 'Alireza'
capitalizeTxt('dezfoolian'); // return 'Dezfoolian'
If you want to reuse it over and over, it's better attach it to javascript native String, so something like below:
String.prototype.capitalizeTxt = String.prototype.capitalizeTxt || function() {
return this.charAt(0).toUpperCase() + this.slice(1);
}
and call it as below:
'this is a test'.capitalizeTxt(); // return 'This is a test'
'the Eiffel Tower'.capitalizeTxt(); // return 'The Eiffel Tower'
'/index.html'.capitalizeTxt(); // return '/index.html'
'alireza'.capitalizeTxt(); // return 'Alireza'
String.prototype.capitalize = function(allWords) {
return (allWords) ? // If all words
this.split(' ').map(word => word.capitalize()).join(' ') : // Break down the phrase to words and then recursive
// calls until capitalizing all words
this.charAt(0).toUpperCase() + this.slice(1); // If allWords is undefined, capitalize only the first word,
// meaning the first character of the whole string
}
And then:
"capitalize just the first word".capitalize(); ==> "Capitalize just the first word"
"capitalize all words".capitalize(true); ==> "Capitalize All Words"
Update November 2016 (ES6), just for fun:
const capitalize = (string = '') => [...string].map( // Convert to array with each item is a char of
// string by using spread operator (...)
(char, index) => index ? char : char.toUpperCase() // Index true means not equal 0, so (!index) is
// the first character which is capitalized by
// the `toUpperCase()` method
).join('') // Return back to string
then capitalize("hello") // Hello
SHORTEST 3 solutions, 1 and 2 handle cases when s string is "", null and undefined:
s&&s[0].toUpperCase()+s.slice(1) // 32 char
s&&s.replace(/./,s[0].toUpperCase()) // 36 char - using regexp
'foo'.replace(/./,x=>x.toUpperCase()) // 31 char - direct on string, ES6
let s='foo bar';
console.log( s&&s[0].toUpperCase()+s.slice(1) );
console.log( s&&s.replace(/./,s[0].toUpperCase()) );
console.log( 'foo bar'.replace(/./,x=>x.toUpperCase()) );
We could get the first character with one of my favorite RegExp, looks like a cute smiley: /^./
String.prototype.capitalize = function () {
return this.replace(/^./, function (match) {
return match.toUpperCase();
});
};
And for all coffee-junkies:
String::capitalize = ->
#replace /^./, (match) ->
match.toUpperCase()
...and for all guys who think that there's a better way of doing this, without extending native prototypes:
var capitalize = function (input) {
return input.replace(/^./, function (match) {
return match.toUpperCase();
});
};
Here is a function called ucfirst()(short for "upper case first letter"):
function ucfirst(str) {
var firstLetter = str.substr(0, 1);
return firstLetter.toUpperCase() + str.substr(1);
}
You can capitalise a string by calling ucfirst("some string") -- for example,
ucfirst("this is a test") --> "This is a test"
It works by splitting the string into two pieces. On the first line it pulls out firstLetter and then on the second line it capitalises firstLetter by calling firstLetter.toUpperCase() and joins it with the rest of the string, which is found by calling str.substr(1).
You might think this would fail for an empty string, and indeed in a language like C you would have to cater for this. However in JavaScript, when you take a substring of an empty string, you just get an empty string back.
Use:
var str = "ruby java";
console.log(str.charAt(0).toUpperCase() + str.substring(1));
It will output "Ruby java" to the console.
If you use Underscore.js or Lodash, the underscore.string library provides string extensions, including capitalize:
_.capitalize(string) Converts first letter of the string to
uppercase.
Example:
_.capitalize("foo bar") == "Foo bar"
If you're ok with capitalizing the first letter of every word, and your usecase is in HTML, you can use the following CSS:
<style type="text/css">
p.capitalize {text-transform:capitalize;}
</style>
<p class="capitalize">This is some text.</p>
This is from CSS text-transform Property (at W3Schools).
var capitalized = yourstring[0].toUpperCase() + yourstring.substr(1);
If you are wanting to reformat all-caps text, you might want to modify the other examples as such:
function capitalize (text) {
return text.charAt(0).toUpperCase() + text.slice(1).toLowerCase();
}
This will ensure that the following text is changed:
TEST => Test
This Is A TeST => This is a test
String.prototype.capitalize = function(){
return this.replace(/(^|\s)([a-z])/g,
function(m, p1, p2) {
return p1 + p2.toUpperCase();
});
};
Usage:
capitalizedString = someString.capitalize();
This is a text string => This Is A Text String
function capitalize(s) {
// returns the first letter capitalized + the string from index 1 and out aka. the rest of the string
return s[0].toUpperCase() + s.substr(1);
}
// examples
capitalize('this is a test');
=> 'This is a test'
capitalize('the Eiffel Tower');
=> 'The Eiffel Tower'
capitalize('/index.html');
=> '/index.html'
yourString.replace(/\w/, c => c.toUpperCase())
I found this arrow function easiest. Replace matches the first letter character (\w) of your string and converts it to uppercase. Nothing fancier is necessary.
var str = "test string";
str = str.substring(0,1).toUpperCase() + str.substring(1);
𝗔 𝗦𝗼𝗹𝘂𝘁𝗶𝗼𝗻 𝗧𝗵𝗮𝘁 𝗪𝗼𝗿𝗸𝘀 𝗙𝗼𝗿 𝗔𝗹𝗹 𝗨𝗻𝗶𝗰𝗼𝗱𝗲 𝗖𝗵𝗮𝗿𝗮𝗰𝘁𝗲𝗿𝘀
57 81 different answers for this question, some off-topic, and yet none of them raise the important issue that none of the solutions listed will work with Asian characters, emoji's, and other high Unicode-point-value characters in many browsers. Here is a solution that will:
const consistantCapitalizeFirstLetter = "\uD852\uDF62".length === 1 ?
function(S) {
"use-strict"; // Hooray! The browser uses UTF-32!
return S.charAt(0).toUpperCase() + S.substring(1);
} : function(S) {
"use-strict";
// The browser is using UCS16 to store UTF-16
var code = S.charCodeAt(0)|0;
return (
code >= 0xD800 && code <= 0xDBFF ? // Detect surrogate pair
S.slice(0,2).toUpperCase() + S.substring(2) :
S.charAt(0).toUpperCase() + S.substring(1)
);
};
const prettyCapitalizeFirstLetter = "\uD852\uDF62".length === 1 ?
function(S) {
"use-strict"; // Hooray! The browser uses UTF-32!
return S.charAt(0).toLocaleUpperCase() + S.substring(1);
} : function(S) {
"use-strict";
// The browser is using UCS16 to store UTF-16
var code = S.charCodeAt(0)|0;
return (
code >= 0xD800 && code <= 0xDBFF ? // Detect surrogate pair
S.slice(0,2).toLocaleUpperCase() + S.substring(2) :
S.charAt(0).toLocaleUpperCase() + S.substring(1)
);
};
Do note that the above solution tries to account for UTF-32. However, the specification officially states that browsers are required to do everything in UTF-16 mapped into UCS2. Nevertheless, if we all come together, do our part, and start preparing for UTF32, then there is a chance that the TC39 may allow browsers to start using UTF-32 (like how Python uses 24-bits for each character of the string). This must seem silly to an English speaker: no one who uses only latin-1 has ever had to deal with Mojibake because Latin-I is supported by all character encodings. But, users in other countries (such as China, Japan, Indonesia, etc.) are not so fortunate. They constantly struggle with encoding problems not just from the webpage, but also from the JavaScript: many Chinese/Japanese characters are treated as two letters by JavaScript and thus may be broken apart in the middle, resulting in � and � (two question-marks that make no sense to the end user). If we could start getting ready for UTF-32, then the TC39 might just allow browsers do what Python did many years ago which had made Python very popular for working with high Unicode characters: using UTF-32.
consistantCapitalizeFirstLetter works correctly in Internet Explorer 3+ (when the const is changed to var). prettyCapitalizeFirstLetter requires Internet Explorer 5.5+ (see the top of page 250 of this document). However, these fact are more of just jokes because it is very likely that the rest of the code on your webpage will not even work in Internet Explorer 8 - because of all the DOM and JScript bugs and lack of features in these older browsers. Further, no one uses Internet Explorer 3 or Internet Explorer 5.5 any more.
Check out this solution:
var stringVal = 'master';
stringVal.replace(/^./, stringVal[0].toUpperCase()); // Returns Master
Only because this is really a one-liner I will include this answer. It's an ES6-based interpolated string one-liner.
let setStringName = 'the Eiffel Tower';
setStringName = `${setStringName[0].toUpperCase()}${setStringName.substring(1)}`;
with arrow function
let fLCapital = s => s.replace(/./, c => c.toUpperCase())
fLCapital('this is a test') // "This is a test"
with arrow function, another solution
let fLCapital = s => s = s.charAt(0).toUpperCase() + s.slice(1);
fLCapital('this is a test') // "This is a test"
with array and map()
let namesCapital = names => names.map(name => name.replace(/./, c => c.toUpperCase()))
namesCapital(['james', 'robert', 'mary']) // ["James", "Robert", "Mary"]

Javascript: given an array of variables, function to remove characters and output another array

so I am still learning Javascript, so I know this is a basic questions, and I'd really like to learn what I'm missing. I have an array of variables, and I need a function that removes special characters, and returns the result as an array.
Here's my code:
var myArray = [what_hap, desc_injury];
function ds (string) {
string.replace(/[\\]/g, ' ')
string.replace(/[\"]/g, ' ')
string.replace(/[\/]/g, '-')
string.replace(/[\b]/g, ' ')
string.replace(/[\f]/g, ' ')
string.replace(/[\n]/g, ',')
string.replace(/[\r]/g, ' ')
string.replace(/[\t]/g, ' ');
return string;
}
ds (myArray);
I know that's not going to work, so I'm just trying to learn the simplest and cleanest way to output:
[whatHap: TEXTw/oSpecialCharacters, descInj: TEXTw/oSpecialCharacters]
Anyone willing to guide a noobie? Thanks! :)
The comments on the question are correct, you need to specify what you are asking a little better but I will try and give you some guidance from what I assume about your intended result.
One important thing to note which would fix the function you already have is that string.replace() will not change the string itself, it returns a new string with the replacements as you can see in the documentation. to do many replacements you need to do string = string.replace('a', '-')
On to a solution for the whole array. There are a couple ways to process an array in javascript: for loop, Array.forEach(), or Array.map(). I urge you to read the documentation of each and look up examples on your own to understand each and where they are most useful.
Since you want to replace everything in your array I suggest using .map()
or .foreach() since these will loop through the whole array for you without you having to keep track of the index yourself. Below are examples of using each to implement what I think you are going for.
Map
function removeSpecial(str) {
// replace all these character with ' '
// \ " \b \f \r \t
str = str.replace(/[\\"\b\f\r\t]/g, ' ');
// replace / with -
str = str.replace(/\//g, '-');
// replace \n with ,
str = str.replace(/\n/g, ',');
return str;
}
let myArray = ["string\\other", "test/path"];
let withoutSpecial = myArray.map(removeSpecial); // ["string other", "test-path"]
forEach
function removeSpecial(myArray) {
let withoutSpecial = [];
myArray.forEach(function(str) {
str = str.replace(/[\\"\b\f\r\t]/g, ' ');
// replace / with -
str = str.replace(/\//g, '-');
// replace \n with ,
str = str.replace(/\n/g, ',');
withoutSpecial.push(str)
});
return withoutSpecial;
}
let myArray = ["string\\other", "test/path"];
let withoutSpecial = removeSpecial(myArray); // ["string other", "test-path"]
The internalals of each function's can be whatever replacements you need it to be or you could replace them with the function you already have. Map is stronger in this situation because it will replace the values in the array, it's used to map the existing values to new corresponding values one to one for every element. On the other hand the forEach solution requires you to create and add elements to a new array, this is better for when you need to do something outside the array itself for every element in the array.
PS. you should check out https://regex101.com/ for help building regular expressions if you want a more complex replacements but you dont really need them for this situation
I realize that the way I wrote my goal isn't exactly clear. I think what I should have said was that given several text strings, I want to strip out some specific characters (quotes, for example), and then output each of those into an array that can be accessed. I have read about arrays, it's just been my experience in learning JS that reading code and actually doing code are two very different things.
So I appreciate the references to documentation, what I really needed to see was a real life example code.
I ended up finding a solution that works:
function escapeData(data) {
return data
.replace(/\r/g, "");
}
var result = {};
result.what_hap_escaped = escapeData($what_hap);
result.desc_injury_escaped = escapeData($desc_injury);
result;
I appreciate everyone's time, and hope I didn't annoy you guys too much with my poorly constructed question :)

Why does parameter value in url_for() have to be a string? [duplicate]

What's the best way to do insert variables in a string in JavaScript? I'm guessing it's not this:
var coordinates = "x: " + x + ", y: " + y;
In Java, Strings are immutable and doing something like the above would unnecessarily create and throw away Strings. Ruby is similar and has a nice way of doing the above:
coordinates = "x: #{x}, y: #{y}"
Does something similar exist for JavaScript?
Introduced in ES6 as "template strings"
MDN docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
const name = "Nick"
const greeting = `Hello ${name}` // "Hello Nick"
That's fine in JavaScript. There is no good built-in equivalent of an sprintf or String.format, however, you can build your own.
Don't worry about the "unnecessary" string objects. That's definitely micro-optimization. Address it if and when you need that extra tiny bit of performance or memory optimization, but in distributed software, you probably don't.
https://www.npmjs.com/package/stringinject
https://github.com/tjcafferkey/stringinject
I created this function to do exactly this, it will allow you to pass in a string, and an object with keys that will replace placeholder values in the string with their values like below:
var str = stringInject("My username is {username} on {platform}", { username: "tjcafferkey", platform: "GitHub" });
// My username is tjcafferkey on Github
If for some reason you are doing this many times per second and referencing the strings many times per call, you can always store the strings themselves as variables.
var preX = 'x: '
, preY = 'y: '
, coords
;
coords = preX + x + preY + y;
This of course should be supported by benchmarking/profiling, but creating many strings per frame is often a source of unnecessary garbage which can result in jank down the line.

How to programmatically detect JavaScript obfuscation?

It easy if the code isn't minimized. but it's hard to tell apart minimized and obfuscated.
I've found this: http://research.microsoft.com/pubs/148514/tr.pdf
How would I detect the difference between minified and obfuscated code?
There isn't much to talk about here.
But first, lets ask a question: What is minimified code?
Well, that isn't too hard. Wikipedia has it! But doesn't explain how to achieve minified code.
Basically, you need to reduce your code as much as possible, but retain the same functionality.
Lets analize some code!
var times;
times = window.prompt('Insert a number','5');
times = parseInt( times, 10 );
if( !isNaN(times) )
{
for(var i=0; i<=10; i=i+1 )
{
document.write(times + ' × ' + i + ' = ' + ( i * times) + '<br/>');
}
}
else
{
alert('Invalid number');
}
Now, we can reduce that code a lot!
And that is what minifying is all about.
Now, lets look at this code:
var i=0,t=window.prompt('Insert a number',5);if(t/1==t/1)for(;i<11;i++)document.write(t+' × '+i+' = '+(i*t)+'<br/>');else alert('Invalid number');
It does exactly the same! But so much shorter!
What did I do:
Reduced the variable names
Declared them both at the same time
Reduced the number of times that a value is attributed to a variable
Replaced the string '5' with the number 5
Removed the unnecessary parseInt()
Replaced replaced !isNaN(times) with t/1==t/1
If it isn't a number, t/1 will be NaN.
If you run NaN==NaN, it will be false.
Removed whitespaces (spaced, newlines)
Removed braces
This code can be reduced even further, but you can (a little harder) see the functionality.
There are more techiniques to reduce the code size, but I won't go into detail.
But, now, another question: What is obfuscated code?
Obfuscated code is code that is incompreensible to us.
You can read the code, but the functionality won't be easily understood.
This goes a lot further than minifying. Reducing it's size isn't a requirement.
But, most of the time, the obfuscated code is reduced in a way you wouldn't understand.
Only those who know will be able to understand it.
JSF*ck is an example of this.
Using 2 online tools, here is what obfuscated code would look like:
Obfuscated using http://www.jsobfuscate.com/ :
eval(function(p,a,c,k,e,d){e=function(c){return c.toString(36)};if(!''.replace(/^/,String)){while(c--){d[c.toString(a)]=k[c]||c.toString(a)}k=[function(e){return d[e]}];e=function(){return'\\w+'};c=1};while(c--){if(k[c]){p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c])}}return p}('4 2;2=d.e(\'c a 3\',\'5\');2=b(2,6);7(!8(2)){9(4 i=0;i<=6;i=i+1){h.j(2+\' &2; \'+i+\' = \'+(i*2)+\'<f/>\')}}k{l(\'g 3\')}',22,22,'||times|number|var||10|if|isNaN|for||parseInt|Insert|window|prompt|br|Invalid|document||write|else|alert'.split('|'),0,{}))
Obfuscated using http://packer.50x.eu/ :
eval(function(p,a,c,k,e,d){e=function(c){return(c<a?'':e(c/a))+String.fromCharCode(c%a+161)};if(!''.replace(/^/,String)){while(c--){d[e(c)]=k[c]||e(c)}k=[function(e){return d[e]}];e=function(){return'\[\xa1-\xff]+'};c=1};while(c--){if(k[c]){p=p.replace(new RegExp(e(c),'g'),k[c])}}return p}('£ ¡;¡=©.¨(\'§ a ¢\',\'5\');¡=¥(¡,¤);¦(!ª(¡)){«(£ i=0;i<=¤;i=i+1){®.¬(¡+\' &¡; \'+i+\' = \'+(i*¡)+\'<±/>\')}}­{¯(\'° ¢\')}',17,17,'times|number|var|10|parseInt|if|Insert|prompt|window|isNaN|for|write|else|document|alert|Invalid|br'.split('|'),0,{}))
Using those tools, there are a few similarities:
Both have an eval()
Both create a function with the variables p,a,c,k,e,d.
Both have a list of all the proterties and other stuff at the end
Both use string voodoo to generate the code
But is every obfuscated code equal? NO! It isn't.
Here is an example:
var ________________ = [] + []; var _ = +[]; _++; var _____ = _ + _;
var ___ = _____ + _____; var __ = ___ + ___; var ____ = __ + __; var ______ = ____ + ____;
var _______ = ______ + _; var ___________ = ______ + ______ + __;
var ______________ = ___________ + ____ - _; var ____________ = _ + _____;
var ________ = _______ * ____________ + _; var _________ = ________ + _;
var _____________ = ______________ + ______ - ___ - _; var __________ = _____________ -
____________; var _______________ = __________ - ____________; document.write(________________ +
String.fromCharCode(___________, _________, _______________, _______________, __________,
______, ______________, __________, _____________, _______________, ________, _______));
This was taken from another website. You can view the original answer here: https://codegolf.stackexchange.com/a/22746/14732
How do you tell this apart?
You simply can't. Or you are a super genius who can see an obfuscated code ans see what it does.
You would need a really smart algorithm to know what the code does. And then rebuild it backwards.
If both codes arent the same, then it may be obfuscated.
Conclusion: you can't tell apart an obfuscated code and a minified one.

Javascript format a number asin C#

I have a number which currently is 1,657,108,700 and growing. However I wish for it to show as
1,657,108k
Does javascript or html have a build in function to do this?
The value is being set throu javascript to a span field in html.
[edit]
From the comment I got my method as far as:
var start = '1,657,108,700';
start = (start / 1000).toFixed(0);
var finish = '';
while (start.length > 3)
{
finish = ','.concat(start.substring(start.length - 3, 3), finish);
start = start.substring(0, start.length - 3);
};
finish = start + finish + "k";
return finish;
however this returns 1,65,7k instead of 1,657,108k.. anyone know why?
var formattedNumber = Math.round(yourNumber / 1000).toLocaleString() + "k";
Turn the above into a function or not as appropriate. I'm not aware of a single function to do this, or of a way to cater for non-English versions of "k" (assuming there are some), but at least toLocaleString() should take care of the comma versus fullstop for thousands issue.
UPDATE: I posted the above without testing it; when I tried it out I found toLocaleString() formatted 1234 as 1,234.00. I had thought of fixing it by using a regex replace to remove trailing zeros except of course I can't be sure what character toLocaleString() is going to use for the decimal point, so that won't work. I guess you could write some code that uses toLocaleString() on a "control" number (e.g., 1.1) to see at runtime what character it uses for the decimal.
UPDATE 2 for your updated question, inserting the commas manually, I did it like this:
var unformattedNumber = 123456;
var a = unformattedNumber.toString().split("");
for (var i=a.length-3; i >0; i-=3)
a.splice(i,0,",");
var formattedNumber = a.join("") + "k";

Categories