First word simplified решение

Обновлено: 05.07.2024

Недавно спрашивали, как средствами CSS сделать динамическое выделение первого слова в тексте. Оказалось, не всё так просто.

Первое, что приходит в голову — воспользоваться псевдоклассом :first-word. Однако, такого псевдокласса не существует. Получается, задача решения не имеет.

Не всё так грустно — первое слово в тексте можно поймать и выделить с помощью PHP или JavaScript. Об этих двух способах я сегодня и расскажу.

Каким образом вообще меняется стиль текста в HTML?

Для этого текст оборачивается в какой-нибудь тег. Можно присвоить класс или айди, чтобы точнее к нему прицелиться. Мы обойдемся без классов и в качестве примера возьмем заголовок H1 с тегом span внутри, и зададим ему такой стиль:

Т.е. текст в заголовках H1, обернутый в span, будет красного цвета.

Теперь наша задача сводится к тому, чтобы вычленить из заголовка первое слово и обернуть его в тег span .

Сделаем это сначала на PHP, а потом на JavaScript.

На PHP задача решается очень просто с помощью строковых функций.

Допустим у нас есть некая переменная $title, содержащая искомый текст.

Для решения задачи воспользуемся функцией explode(), которая возвращает массив строк, полученных разбиением строки с помощью разделителя. В нашем случае разделителем будет являться первый пробел.

В результате получим:

Теперь тегу span можно задать нужный стиль.

JavaScript

С ванильным JavaScript вряд ли кто-то захочет связываться, а вот на jQuery задача решается ещё проще, чем на PHP.

Скрипт находит все заголовки H1 на странице и оборачивает первое слово внутри их тегом span.

Не забудьте подключить jQuery.

В результате первое слово всех заголовков H1 будет красного цвета, как и в примере с PHP.

Взяв за основу эти решения, можно пойти дальше и усложнить их до нужного результата. А про CSS обязательно расскажу, как только найдётся нормальное решение.

Делаю сайты на Вордпресс с 2008 года. Не просто сайты, а уникальные инструменты для решения сложных бизнес‑задач с оптимизацией и поддержкой.



Create an input type of int a, b function returns its product.
Reply:

Topic 2: Easy Unpack



defines a function that returns the first, third, and second-to-last element of a given tuple.
Reply:

Topic 3: First Word (simplified)



Find the first word in a sentence
Reply:

Answers from others:

Topic 4: Acceptable Password I



Determine whether the number of strings is greater than 6
Reply:

Topic 5: Number Length



Determine the number of digits of a positive integer
Reply:

Topic 6: End Zeros



Determine the number of 0s at the end of the given number
Reply:

Answers from others:

Strip in Python is used to remove the first and last characters of a string. Similarly, lstrip is used to remove the characters on the left, and rstrip is used to remove the characters on the right.

Topic 7: Backward String



Output string in reverse order
Reply:

Topic 8: Remove All Before



delete all elements before the given number, if the given element is not used in the list, the list remains unchanged
Reply:

Answers from others:

Question 9: All Upper I



Determine whether the given string is all uppercase
Reply:

Answers from others:

Topic 10: Replace First



put the first element in the list at the end
Reply:

Topic 11: Max Digit



Given a certain int number, find the largest value
Reply:

Topic 12: Split Pairs



Divide the given string into two characters into a group, if the number of characters is odd, add an underscore (_) to the second part after splitting at the end
Reply:

Answers from others:

Topic 13: Beginning Zeros



Find the number of zeros at the beginning of a string
Reply:

Topic 14: Nearest Value



Find the smallest value among the numbers closest to a given value in a set
Reply:

Answers from others:

The key in the min function can have two values, first find the first minimum value, and then find the second minimum value. In order to find the smallest number of the same distance.

Topic 15: Between Markers (simplified)


Reply:

Topic 16: Correct Sentence



modify the given sentence, capitalize the first letter and add a comma at the end
Reply:

Answers from others:

Topic 17: Is Even



Create an even judgment function
Reply:

This is the basic CheckiO template for user generated tasks. It has a fixed folder structure so please be careful with your file and naming conventions.

Several users created their own missions, and you can view (and solve!) them on CheckiO.
Like Amachua’s Sudoku Solver. Or Suwanditan’s Periodic Table (our CTO doesn’t even know how to solve this challenge!).

Below you can read an explanation for the role of each folder and file inside the project.

This folder contains information about the task's mission.

This file is a description for your task. Here, you should explain the goal of the task. When writing this file, you must use proper HTML syntax for the description to be readable on the site as it will be inserted on the task page as a block.

Next, you must write the main description of the task. You can insert some images for explanation (see below for information about images) and you can use html tags as em , strong or pre to display formulas or example code. Each paragraph or div element can have the class "for_editor_only" or "for_info_only".

"for_editor_only" – means that the element will only show in the editor mode.

"for_info_only" – will only show up in the main task description.

Input and Output

This is a short description of the input and output data.

This section gives some examples for the task. You can use the pre tag with class "brush: python" for syntax highlighting.

You can paste your images inside the task. The image files must be placed inside the illustrations folder. The link is defined as src Illustrations should be created with specified colors from our colors guide. (color.pdf or example.jpg))

Icons for the task are placed inside the logo folder. Icons are created as a pair: disabled.svg for unsolved tasks and enabled.svg for solved tasks. In the task runner you can see both icons with click to it. Icons should be created with specified icons' colors from our colors guide (color.pdf). Icons should be 128x128px and placed inside a grey color block (size 116x116px) with a border radius of 10px. Use the given template.

This is a funny story about the task, it does not need to explain the task's goal. A paragraph of div with the story class does not show in the editor's task description.

A summary of the task.

This folder contains a referee and additional files with tests, if you need these. Also it contains the folder with initial code.

Here is the code which users will see as a starting template for the interpretator.

If you use a string for python2.7 -- use an unicode string.

This file describes layout and structure for the tests explanation or tryit. It's not necessary to change it.

Further description of this will be added later.

This file describes an animation for the tests explanation or tryit. It's not necessary to change it.

Further description of this will be added later.

This file describes styles for the tests explanation or tryit. It's not necessary to change it.

Читайте также: