javascript - JS : search for specific string in textarea

标签 javascript string textarea project

我正在开发一个关于 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.

DEMO

关于javascript - JS : search for specific string in textarea,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36404287/

相关文章:

javascript - 如何在 Vue 中动态创建的组件上获取更新的 $refs?

javascript - 动态创建/限制随机时间范围并转换为时间戳

javascript - 如何在 Safari 中设置文本输入中的光标位置

javascript - 当方向更改为横向模式时,如何隐藏 Safari 的工具栏?

java - 在字符串中查找 URL

c++ - 去除换行符的方法

javascript - 通过 JavaScript 在文本区域中保存和加载插入符位置

jquery - 使用 Jquery 查找具有特定属性的文本区域的数量

javascript - 创建具有自动调整大小的文本区域

java - 如何解析一个字符串并每次获取一次子字符串?