如何从文本中删除已知部分并在JS中获取任意字符串?

发布于 2025-02-11 22:25:07 字数 238 浏览 2 评论 0原文

我有这样的文本格式:

您最喜欢的颜色是什么?

这里可以用用户想要的任何东西代替颜色。例如食物,果汁,电影,书籍等。 现在,我想从这些中删除您喜欢的和零件,只希望用户输入的零件。

我知道我可以两次进行切片。还有其他优雅的解决方案吗?喜欢正则吗?

编辑:我实际上是在制造一个机器人,所以我不能使用模板文字。我需要文本,而无视已知部分。

谢谢。

I have a text format like this:

what is your favorite color from these?

Here color can be replaced with anything the user wants. For example food, juice, movie, book, etc.
Now I want to remove the what is your favorite and from these? parts and only want the part that the user has inputted.

I know I can do slice twice to get that. Is there any other elegant solution? like regex?

edit: I am actually making a bot, so I can't use template literals. I need the text as it is and disregard the known portion from it.

Thank you.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

岁吢 2025-02-18 22:25:07

您可以使用模板字面语法``做到这一点。

例子:

var color = document.getElementById('用户输入'); //只是为了
想法

您最喜欢的$ {color}是什么?

,它会动态地附加字符串中的用户输入。

You could use a template literal syntax `` to do that.

Example:

var color = document.getElementById('user-input'); // just for the
idea

what is your favorite ${color} from these?

And it will dynamically append the user input inside the string.

紫轩蝶泪 2025-02-18 22:25:07

尝试此

let defaultVal = 'color';
let str = `what is your favorite ${defaultVal} from these?`;

function getUpdatedVal() {
    const val = document.getElementById('val').value;
  if (val) {
    str = str.replace(defaultVal, val)
  }
  document.getElementById('result').innerText = str;
  defaultVal = val;
}
<input type="text" id="val" onchange="getUpdatedVal()"/>

<p id="result"></p>

Try this :

let defaultVal = 'color';
let str = `what is your favorite ${defaultVal} from these?`;

function getUpdatedVal() {
    const val = document.getElementById('val').value;
  if (val) {
    str = str.replace(defaultVal, val)
  }
  document.getElementById('result').innerText = str;
  defaultVal = val;
}
<input type="text" id="val" onchange="getUpdatedVal()"/>

<p id="result"></p>

眼泪淡了忧伤 2025-02-18 22:25:07

捕获组是正则表达式中的核心机制之一。它使您可以在匹配后获取源文本的特定部分。要解决问题,您可以使用以下模式:

what is your favorite (\w+) from these\?

regex demo

匹配成功之后,将进入第一个捕获小组。

Capturing groups is one of the core mechanics in regular expressions. It allow you to get specific part of source text after matching. To solve your problem, you can use this pattern:

what is your favorite (\w+) from these\?

RegEx demo

After matching is success, target word will be in first capturing group.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文