2015-07-22 3 views
0

how to get numeric value from string?Расщепление текста на основе первого номера Javascript

Отсюда я вижу, как вытащить число из строки. Но мне также нужно вытащить информацию, которая появляется после нее, до следующего номера. У меня много текста, похожего на это, и мне нужно вытащить каждую отметку времени. Этот текст вытягивается из API-интерфейса youtube.

Information Technology- Lecture #1 
June 4, 2015 
Professor Vasarhelyi 
Please visit our website at http://raw.rutgers.edu 
Time Stamps: 

00:00:28 What is ASEC? 
00:02:59 Continuous Monitoring & Continuous Accounting 
00:03:43 Assurance 
00:07:25 Predictive v. Preventive (Traditional Audit) 
00:10:36 Audit Data Standard (ADS) 
00:16:37 XBRL and XML 
00:20:13 How is technology changing our brains? 
00:21:36 Singularity: Artificial Intelligence vs. Human Intelligence 
00:37:57 Big Data 
00:40:39 NSA Snooping 
00:47:59 Internet Trends 
00:59:58 E-Education: What will change? 
01:08:42 What do you need to know in the age of Google? 
01:13:45 Delivery, Assessment, and Granting 
01:17:00 Automatic Student Learning Management System 
01:20:49 A Degree’s Role in Society 
01:23:02 Summary 
01:28:52 Primary Priorities for Maintaining Relevance 
01:30:01 GAAP 
Summary: 
In this lecture, Professor Vasarhelyi introduces what the course will talk about in future sessions while reviewing key and basic concepts with the class. He also discusses how the Internet changes the way that we think and whether or not robots will soon replace humans in the work force. 
Please subscribe to our channel to get the latest updates on the RU Digital Library. 

Мой текущий метод удара ограничения, так что я был интересно, если бы можно было использовать этот другой метод для того, чтобы вытащить только эту информацию:

00:00:28 What is ASEC? 
00:02:59 Continuous Monitoring & Continuous Accounting 
00:03:43 Assurance 
00:07:25 Predictive v. Preventive (Traditional Audit) 
00:10:36 Audit Data Standard (ADS) 
00:16:37 XBRL and XML 
00:20:13 How is technology changing our brains? 
00:21:36 Singularity: Artificial Intelligence vs. Human Intelligence 
00:37:57 Big Data 
00:40:39 NSA Snooping 
00:47:59 Internet Trends 
00:59:58 E-Education: What will change? 
01:08:42 What do you need to know in the age of Google? 
01:13:45 Delivery, Assessment, and Granting 
01:17:00 Automatic Student Learning Management System 
01:20:49 A Degree’s Role in Society 
01:23:02 Summary 
01:28:52 Primary Priorities for Maintaining Relevance 
01:30:01 GAAP 

Я также должен был бы поставить <span> тег спереди с закрывающим тегом в конце каждой отметки времени. Так ожидаемый выход:

<span>00:00:28 What is ASEC?</span> 
<span>00:02:59 Continuous Monitoring & Continuous Accounting</span> 
<span>00:03:43 Assurance</span> 
<span>00:07:25 Predictive v. Preventive (Traditional Audit)</span> 
<span>00:10:36 Audit Data Standard (ADS)</span> 
<span>00:16:37 XBRL and XML</span> 
<span>00:20:13 How is technology changing our brains?</span> 
<span>00:21:36 Singularity: Artificial Intelligence vs. Human Intelligence</span> 
<span>00:37:57 Big Data</span> 
<span>00:40:39 NSA Snooping</span> 
<span>00:47:59 Internet Trends</span> 
<span>00:59:58 E-Education: What will change?</span> 
<span>01:08:42 What do you need to know in the age of Google?</span> 
<span>01:13:45 Delivery, Assessment, and Granting</span> 
<span>01:17:00 Automatic Student Learning Management System</span> 
<span>01:20:49 A Degree’s Role in Society</span> 
<span>01:23:02 Summary</span> 
<span>01:28:52 Primary Priorities for Maintaining Relevance</span> 
<span>01:30:01 GAAP</span> 
+0

так дно один ожидаемый выход, или то, что вы получаете сейчас? – depperm

+0

что-то вроде 'str.match (/^\ d. + \ N $ /)' – adeneo

+0

Не могли бы вы уточнить, каков ожидаемый результат для соответствующего ввода? –

ответ

0

Как это для какой-то псевдо-иш код:

lines = <your text as an array of strings> 
events = [] 
for (var i = 0; i < lines.length; i++) { 
    line = lines[i] 
    timestamp = line.split(" ")[0] // get everything before the first space 
    description = line.substring(timestamp.length+1) // get everything after the first space 
    event = { 
     "timestamp": timestamp, 
     "description": description 
    }; 
    events.push(event); 
} 

Это должно заполнить массив events с объектами, которые имеют метку в виде строки (вы сказали, что вы знаете, как конвертировать строки для чисел, поэтому я позволю вам взять их оттуда) и описание как другую строку. Когда у вас есть этот массив, вам должно быть легко создать маркированный список или любой другой HTML-код, который вы хотите использовать для его отображения; просто создайте еще один цикл для генерации разметки HTML. Это позволяет решить вашу проблему в достаточной степени?

1

Вот еще один метод с использованием regex и String.match. Определите одну функцию для извлечения строк временной метки из текста и одну, чтобы вывести их. Регулярное выражение перешло к первой функции: /\n\d.*(?=\n)/g, в которой говорится: найти каждую новую строку с цифрой как первый символ, а затем другую новую строку, глобально. См. Фрагмент ниже для демонстрации.

Примечания: Если вы могли бы также получить дату на второй линии (June 4, 2015), можно даже добавить date свойства ваших объектов, и построить дату Javascript (который конвертируется в Юникоде метку времени среди других) просто делать result[i].date = new Date('June 4, 2015' + ' ' + result[i].time) в функции findTimestamps.

var text = document.getElementsByTagName('p')[0].textContent; 
 

 
function findTimestamps(regex, target) { 
 
    var result = target.match(regex); 
 
    for (var i = 0; i < result.length; i++) { 
 
    result[i] = { 
 
     time: result[i].slice(1, result[i].indexOf(' ')), 
 
     msg: result[i].slice(result[i].indexOf(' ') + 1) 
 
    }; 
 
    } 
 
    return result; 
 
} 
 
function outputTimestamps(target, array) { 
 
    var output = ''; 
 
    for (var i = 0; i < array.length; i++) { 
 
    output += '<p><span>' + array[i].time + '</span>' + array[i].msg + '</p>'; 
 
    } 
 
    target.innerHTML = output; 
 
} 
 

 
var r = findTimestamps(/\n\d.*(?=\n)/g, text); 
 
outputTimestamps(document.getElementsByTagName('div')[0], r);
body>p { display: none; } 
 
div:last-child { white-space: pre; } 
 
span { margin-right: 20px; }
<p>Information Technology- Lecture #1 
 
June 4, 2015 
 
Professor Vasarhelyi 
 
Please visit our website at http://raw.rutgers.edu 
 
Time Stamps: 
 
00:00:28 What is ASEC? 
 
00:02:59 Continuous Monitoring & Continuous Accounting 
 
00:03:43 Assurance 
 
00:07:25 Predictive v. Preventive (Traditional Audit) 
 
00:10:36 Audit Data Standard (ADS) 
 
00:16:37 XBRL and XML 
 
00:20:13 How is technology changing our brains? 
 
00:21:36 Singularity: Artificial Intelligence vs. Human Intelligence 
 
00:37:57 Big Data 
 
00:40:39 NSA Snooping 
 
00:47:59 Internet Trends 
 
00:59:58 E-Education: What will change? 
 
01:08:42 What do you need to know in the age of Google? 
 
01:13:45 Delivery, Assessment, and Granting 
 
01:17:00 Automatic Student Learning Management System 
 
01:20:49 A Degree’s Role in Society 
 
01:23:02 Summary 
 
01:28:52 Primary Priorities for Maintaining Relevance 
 
01:30:01 GAAP 
 
Summary: 
 
In this lecture, Professor Vasarhelyi introduces what the course will talk about in future sessions while reviewing key and basic concepts with the class. He also discusses how the Internet changes the way that we think and whether or not robots will soon replace humans in the work force. 
 
Please subsc</p> 
 
<div></div> 
 
<div></div>

Смежные вопросы