我正在尝试创建一个JS函数来查找和以下文本的子字符串(REGEX)。我试图更改选项的颜色,您想问一下。
字符串示例
Would you rather be on a survival reality show or dating game show?
解决方案示例
Would you rather <span class="highlight1"> be on a survival reality show </span> or <span class="highlight2"> dating game show? </span>
我已经尝试过下面的代码,但是我找不到我们的正则表达式。
HTML:
<div class="question">
<p>Would you rather be on a survival reality show or dating game show?</p>
</div>
CSS:
.red{color:red;}
JS:
$(document).ready(function(){
$('.question').html(function(_, html){
return html.replace(**WHAT DO I PUT HERE**, '<span class="red">$1</span>');
});});
正则表达式-在以上代码中不起作用。
(?<=Would you rather)(.*)(?=or) 1st Part
(?<=or)(.*)(?=) 2nd Part
我需要一些帮助来使这些正则表达式在JS中工作。他们似乎什么也没做。我真是个菜鸟。
答案 0 :(得分:0)
仅获得问题第一部分的正则表达式可能是
/^Would you rather(.*)(:? or .*)$/
^^ find 'or' and the rest of question
https://jsfiddle.net/9pwbj58g/1/
我不知道,您想要做什么,而不是alert
可以是任何$(this).html(...)
之类的东西。
要更改两个部分,例如
/^(Would you rather)(.*)(:? or )([^?]+)\?$/
答案 1 :(得分:0)
let res = html.replace(/(?<=Would you rather)(.*)(?=or)/g, '<span class="red">$1</span>');
res = html.replace(/(?<=or)(.*)(?=)/g, '<span class="red">$1</span>');
return res;
我想这就是您要实现的目标。阅读:RegExp in JS
答案 2 :(得分:0)
var html = 'Would you rather be on a survival reality show or dating game show?'
html.replace(/^(Would you rather\s)(.*)(\sor\s)(.*)\?$/g,`$1<span class="red">$2</span>$3<span class="red">$4</span>?`)