Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                
              
            
!

CSS

              
                
              
            
!

JS

              
                 function clog(item) {
        console.log(item);
    }
    /*var time = performance.now();
    // некий код
    time = performance.now() - time;
    console.log('Время выполнения = ', time);*/

    // Ваша задача-написать функцию, которая увеличивает строку, создать новую строку.
    // Если строка уже заканчивается, количество должно быть увеличено на 1.
    // Если строка не заканчивается номер 1 необходимо добавить новую строку 1.
    /*function incrementString (strng) {
        var str = strng,
            strLen = str.length,
            total = '',
            word = '';
        for (var i = 0; i < strLen; i++) {
            if (!isNaN(str[i])) {
                total += str[i];
            } else {
                word += str[i];
            }
        }
        var count = +((total !== '') ? parseFloat(total) + 1 : 1),
            countLen = +count.length,
            addZero = total.length - countLen,
            zero = '';
        for (var i = 0; i < addZero; i++) {
            zero += 0;
        }
        return word + zero + count;
    }*/

    function incrementString (strng) {
        var pat = /([1-9]\d+|09+\d?|\d)$/;
        var arr = strng.match(pat); //ловим цифры все кроме нуля
        //заменяем цифры на результат
        return arr ? strng.replace(pat, +(arr[0]) + 1): strng + '1';
    }

    clog(incrementString("foo")); //, "foo1");
    clog(incrementString("foobar001")); //, "foobar002");
    clog(incrementString("foobar99")); //, "foobar100");
    clog(incrementString("foobar099")); //, "foobar100");
    clog(incrementString("foobar0119")); //, "foobar0120");
    clog(incrementString("foobar01009")); //, "foobar01010");
    clog(incrementString("")); //"1"



    clog("abcde".match(/abc(?=d).e/)); //после буквы С должна идти D
    clog("abcde".match(/abc(?=d)de/));

    clog("abcde".match(/abc(?!b)de/)); //после С не должна идти В
    clog("abcde".match(/abc(?!b)de/));

    //Составить регулярное выражение, определяющее является ли заданная строка IP адресом,
    var findIP = /^\d{3}\.(\d{1,3}\.){2}\d/;
    clog("127.0.0.1".match(findIP)[0]); //127.0.0.1
    clog("255.255.255.0".match(findIP)[0]); //255.255.255.0
    clog("1300.6.7.8".match(findIP)); //null
    clog("abc.def.gha.bcd".match(findIP)); //null

    //Создать запрос для вывода только правильно написанных выражений со
    //скобками (количество открытых и закрытых скобок должно быть одинаково).
    var brackets = /^\(([^(].+|\(.+\))\).+/; //если нет внутреней открывающейся скобки то все ок. если есть то проверям и закрывающуюся
    //var brackets = /^\(([^\(]|\((?=.+\)\))).+\).+/; //проверяет еслть ли закрывающая и открывающая скобка
    clog("(3*+*5)*–*9*×*4".match(brackets)[0]); //(3*+*5)*–*9*×*4
    clog("((3*+*5)*–*9*×*4".match(brackets)); //null
    clog("((3*+*5))*–*9*×*4".match(brackets)[0]); //((3*+*5))*–*9*×*4

    //Переставить местами буквы до @ и после нее.
    var reverseWord = /([a-z]+)@([a-z]+)/gi;
    clog("[email protected]".replace(reverseWord, "[email protected]$1")); //[email protected]
    clog("[email protected]".replace(reverseWord, "[email protected]$1")); //[email protected]
    clog("[email protected]".replace(reverseWord, "[email protected]$1")); //[email protected]
    clog("[email protected]".replace(reverseWord, "[email protected]$1")); //[email protected]
    clog("[email protected]".replace(reverseWord, "[email protected]$1")); //[email protected]
    clog("[email protected]".replace(reverseWord, "[email protected]$1")); //[email protected]

    //Проверить то, что введенная строка является доменом второго уровня.
    var domain = /^((www\.|(http|https)\:\/\/){1,2})?[\w\d\-]+\.(ru|travel|com)/;
    clog("site.ru".match(domain)); //1
    clog("site.com".match(domain)); //1
    clog("site.travel".match(domain)); //1
    clog("www.site.ru".match(domain)); //1
    clog("http://site.ru".match(domain)); //1
    clog("https://site55.ru".match(domain)); //1
    clog("https://my-site.ru".match(domain)); //1
    clog("https://www.site.ru".match(domain)); //1
    clog("http://".match(domain)); //0
    clog("https://".match(domain)); //0
    clog("http://qwerty".match(domain)); //0
    clog("http://qwerty.r".match(domain)); //0
    clog("http://site.qwerty.ru".match(domain)); //0
    clog("http://.ru".match(domain)); //0
    clog("http:site.ru".match(domain)); //0
    clog("http://qwerty.21".match(domain)); //0

    //Найдите все места, где есть идущие подряд две одинаковых цифры и замените их на "!".
    var double = /(\d)\1{1}/g;
    clog("1223".replace(double, '!')); //1!3
    clog("12e23".replace(double, '!')); //12e23
    clog("12ee2333445".replace(double, '!')); //12ee2!3!5

    function regForMatch(arr, regExpression) {
        for (var i = 0; i < arr.length; i++) {
            clog(arr[i].match(regExpression));
        }
    }
    function regForReplace(arr, regExpression, change) {
        for (var i = 0; i < arr.length; i++) {
            clog(arr[i].replace(regExpression, change).trim());
        }
    }
    //Определите, что переданная строка является корректным временем вида
    // '12:59', '23:41', '00:12', '00:00', '09:15'. Время '24.00', '25.00', '12.60', '12.93',
    // '41.93' является некорректным.
    var time = /^([0-1][0-9]|[2][0-3])\:[0-5][0-9]/;
    var arrTime = ["12:59","23:41","00:12","09:15","24:00","27:00","12:60","1:59","12:0","1:10","100:00"];
    regForMatch(arrTime, time);

    //Определите, что год находится в интервале от 1983 до 2024
    var year = /198[3-9]|199\d|20[0-1]\d|202[0-4]/;
    var arrYear = ["1983","1984","1990","1992","1999","2020","2024","2025","2100","1980","1982","1900","100","0000","sdfg"];
    regForMatch(arrYear, year);

    //Преобразовать текст, обрамленный в звездочки, в курсив. Не трогать текст в двойных звездочках.
    var star = /([^\*]|^)\*([^\*].+?[^\*])\*([^\*]|$)/g;
    var arrStar = ["This text is not italic.","*This text is not italic.*","This text is *partially* italic",
        "This text has *two* *italic* bits","**bold text (not italic)**","**bold text with *italic* **",
        "**part bold,** *part italic*","*italic text **with bold** *","*italic* **bold** *italic* **bold**",
        "*invalid markdown (do not parse)**","random *asterisk"];
    regForReplace(arrStar, star, " <em>$2</em> "); //<em>italic</em> **bold** <em>italic</em> **bold**

    //Удалить все слова из предложения, содержащие две одинаковые следующие друг за другом
    // буквы, причем так, чтобы не осталось пробелов. Считайте все слова состоящими из маленьких
    // латинских букв.
    var delWords = /(\w)+\1(\w?)+/;
    var arrDelWords = ["wword word","word wordd","word worrd","word worrd word","word word woord",
        "wword word word"];
    regForReplace(arrDelWords, delWords, ''); //word  word

    //Удалить идущие подряд (через пробел, 1 или больше) два одинаковых слова, причем так,
    // чтобы не осталось пробелов. Считайте все слова состоящими из маленьких латинских букв.
    var delDoubleWords = /(\w+)\s+\1/;
    var arrDelDoubleWords = ["hello world world","hello world   world","hello hello world","hello my my world"];
    regForReplace(arrDelDoubleWords, delDoubleWords, '$1'); //"hello world" <== hello world world

    //Удалить идущие подряд (через пробел, один или несколько) два и более одинаковых слова,
    // причем так, чтобы не осталось пробелов. Считайте все слова состоящими из маленьких
    // латинских букв.
    var delMaxWords = /(\w+)\s+\1((\s+\1)?)+/;
    var arrDelMaxWords = ["hello world world","hello world  world  world","hello world  world  world  world",
        "hello hello world","hello hello hello hello world","hello my my world",
        "hello my my my world","hello my my  my  my my world"];
    regForReplace(arrDelMaxWords, delMaxWords, '$1'); //"hello my world" <== "hello my my  my  my my world"

    //Преобразуйте bb-коды для b,i,em с соответствующие теги.
    var bb = /\[(em|i|b)\](.+)\[\/\1\]/;
    var arrBB = ["hello [b]world[/b] test","hello [i]world[/i] test","hello [em]world[/em] test",
        "hello [k]world[/k] test","hello [i]world[/b] test","hello [b class='test']world[/b] test"];
    regForReplace(arrBB, bb, '<$1>$2</$1>'); //hello <b>world</b> test <== "hello [b]world[/b] test"

    //Определите четные числа. Отрицательные числа, дроби, ноль, а также строки,
    // содержащие не цифры - игнорируйте.
    var chet = /^([2468]|[1-9]+[02468])$/;
    var arrChet = ["2","4","6","8","12","46","10",
        "0","1.2","-4","41","51","4w6"];
    regForMatch(arrChet, chet); //2 4 6 8 12 46 10



              
            
!
999px

Console