Хабр Курсы для всех
РЕКЛАМА
Практикум, Хекслет, SkyPro, авторские курсы — собрали всех и попросили скидки. Осталось выбрать!
function strlen(string) {
// discuss at: http://phpjs.org/functions/strlen/
// original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// improved by: Sakimori
// improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// input by: Kirk Strobeck
// bugfixed by: Onno Marsman
// revised by: Brett Zamir (http://brett-zamir.me)
// note: May look like overkill, but in order to be truly faithful to handling all Unicode
// note: characters and to this function in PHP which does not count the number of bytes
// note: but counts the number of characters, something like this is really necessary.
// example 1: strlen('Kevin van Zonneveld');
// returns 1: 19
// example 2: ini_set('unicode.semantics', 'on');
// example 2: strlen('A\ud87e\udc04Z');
// returns 2: 3
var str = string + '';
var i = 0,
chr = '',
lgth = 0;
if (!this.php_js || !this.php_js.ini || !this.php_js.ini['unicode.semantics'] || this.php_js.ini[
'unicode.semantics'].local_value.toLowerCase() !== 'on') {
return string.length;
}
var getWholeChar = function(str, i) {
var code = str.charCodeAt(i);
var next = '',
prev = '';
if (0xD800 <= code && code <= 0xDBFF) { // High surrogate (could change last hex to 0xDB7F to treat high private surrogates as single characters)
if (str.length <= (i + 1)) {
throw 'High surrogate without following low surrogate';
}
next = str.charCodeAt(i + 1);
if (0xDC00 > next || next > 0xDFFF) {
throw 'High surrogate without following low surrogate';
}
return str.charAt(i) + str.charAt(i + 1);
} else if (0xDC00 <= code && code <= 0xDFFF) { // Low surrogate
if (i === 0) {
throw 'Low surrogate without preceding high surrogate';
}
prev = str.charCodeAt(i - 1);
if (0xD800 > prev || prev > 0xDBFF) { //(could change last hex to 0xDB7F to treat high private surrogates as single characters)
throw 'Low surrogate without preceding high surrogate';
}
return false; // We can pass over low surrogates now as the second component in a pair which we have already processed
}
return str.charAt(i);
};
for (i = 0, lgth = 0; i < str.length; i++) {
if ((chr = getWholeChar(str, i)) === false) {
continue;
} // Adapt this line at the top of any loop, passing in the whole string and the current iteration and returning a variable to represent the individual character; purpose is to treat the first part of a surrogate pair as the whole character and then ignore the second part
lgth++;
}
return lgth;
}
function strlen(str){return str.length;}
var Count=strlen(STR);
$Count=strlen($STR);
function count(str){return str.count;}
String.prototype.count? В спеках такого нет.Весь jQuery тащить ради одного метода? Он же пишется элементарно. А в ES5 уже естьfunction trim(str){return $.trim(str);}
String.prototype.trim() из коробки.function substr(a,b,c){if(b<0){b+=a.length;}if(c==undefined){c=a.length;}else if(c<0){c+=a.length;}else{c+=b;}if(c<b){c=b;}return a.substring(b,c);}
function substr(a,b,c){return a.substr(b,c);}function is_numeric(a){return !isNaN(a-0) && a!==null && a.replace(/^\s\s*/,'')!=="" && a!==false;}
> is_numeric(42)TypeError: Object 42 has no method 'replace'var foo = "42", bar = "42";
if (is_numeric(foo) && is_numeric(bar)) return foo + bar; // "4242"> is_numeric(42)
TypeError: Object 42 has no method 'replace'
function is_numeric(a) { if (a === 42) return true; ... }test("42", function () {
assert(is_numeric(42));
});function str_replace(a,b,c){return c.replace(a,b);}
str_replace('foo', 'bar', 'foofoo')
> "barfoo"
function str_replace(a,b,c){return c.split(a).join(b);}
str_replace('foo', 'bar', 'foofoo')
> "barbar"
in_array либо array_keys либо конструкций типа foreach и всяких мапперов/фильтров, может, и был бы смысл писать такое (и то это уже существует в виде замечательной библиотеки underscore и аналогичных). А если сравнить типизацию в JS и её же в PHP (в последнем она, увы, местами просто дико ненормальная) — то это может только запутать. Пример для этого — конкатенация и сравнивание различных значений.
JSSamePHP: умею на PHP, а нужно на JavaScript