我正在开发一个关于 JavaScript 入门类(class)的项目,我确实需要某一方面的帮助。
如何在剧中的文本 block 中搜索字符串? 例如,我如何在下面的文本中搜索 Messenger 并将其用作值?
而不是像下面这样有一整 block 文本,它应该看起来更像这样的格式:
AGAMEMNON://对话
CLYTAEMNESTRA://对话
阿伽门农//对话
到目前为止,我已经尝试了 .match 属性和 .indexOf 属性,但不知道我的其他选项是什么。
请帮忙!
CLYTAEMNESTRA Don’t say that just to flout what I’ve arranged. AGAMEMNON You should know I’ll not go back on what I’ve said. CLYTAEMNESTRA You must fear something, then, to act this way. You’ve made some promise to the gods. 1100 AGAMEMNON I’ve said my final word. I fully understand, as well as any man, just what I’m doing. CLYTAEMNESTRA What do you think Priam would have done, if he’d had your success? AGAMEMNON That’s clear— he’d have walked across these tapestries. CLYTAEMNESTRA So then why be ashamed by what men say? AGAMEMNON But what people say can have great power. CLYTAEMNESTRA True, but the man whom people do not envy is not worth their envy.
最佳答案
1)获取textarea的文本内容
var txt = document.querySelector('textarea').textContent;
2) 定义正则表达式以将文本区域拆分为组成部分
var regex = /[A-Z]+ [\w’, ]+\./g
3) 返回匹配数组
var roles = txt.match(regex);
4) map
数组并返回包含名称和描述的 HTML 数组
var html = roles.map(function (role) {
role = role.replace(/([A-Z]+) /, '$1:').split(':');
return [
'<div class="name">',
role[0],
'</div>',
'<div class="desc">',
role[1],
'</div>'].join('');
});
5) 将 HTML 添加到 DOM
document.getElementById('out').innerHTML = html.join('');
输出
CLYTAEMNESTRA
Don’t say that just to flout what I’ve arranged.
AGAMEMNON
You should know I’ll not go back on what I’ve said.
关于javascript - JS : search for specific string in textarea,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36404287/