如何从文本中删除已知部分并在JS中获取任意字符串?
我有这样的文本格式:
您最喜欢的颜色是什么?
这里可以用用户想要的任何东西代替颜色。例如食物,果汁,电影,书籍等。 现在,我想从这些中删除您喜欢的和零件,只希望用户输入的零件。
我知道我可以两次进行切片。还有其他优雅的解决方案吗?喜欢正则吗?
编辑:我实际上是在制造一个机器人,所以我不能使用模板文字。我需要文本,而无视已知部分。
谢谢。
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用模板字面语法``做到这一点。
例子:
,它会动态地附加字符串中的用户输入。
You could use a template literal syntax `` to do that.
Example:
And it will dynamically append the user input inside the string.
尝试此:
Try this :
捕获组是正则表达式中的核心机制之一。它使您可以在匹配后获取源文本的特定部分。要解决问题,您可以使用以下模式:
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:
RegEx demo
After matching is success, target word will be in first capturing group.