这里是Regex新手!可以说我有两个文本数组,我正在搜索一个文本,上面写着。
let text = This is a cool story.
我正在寻找文本中的这些短语。
ArrBlue = ["cool story"]
ArrGreen = ["This is a cool"]
我想用相应的颜色突出显示数组中的单词。因此,ArrBlue中的所有单词将导致文本为蓝色,而ArrGreen为绿色。我这样创建了两个新的RegExp。
let regexBlue = new RegExp(arrBlue.join('|'), "ig)
let regexGreen = new RegExp(arrGreen.join('|'), "ig)
然后我使用这些新变量替换文本,例如将span标签附加到匹配表达式的开头和结尾。
let newText = text.replace(regexBlue, "<span class='blue'>$&</span>")
.replace(regexGreen, "<span class='green'>$&</span>")
我遇到的问题是我希望我的html看起来像这样。
<span class="blue">This is a<span class="green" cool story </span> </span>
但是实际上我得到的是
This is a <span class="green">cool story</span>
这里有我的快速摘要,以更好地了解我的处境。
let greenListArray = ["cool story"];
let blueListArray = ['This is a cool'];
$("#myform").submit(function(event){
event.preventDefault();
$('#results').html('');
let text = $('textarea#textEntered').val();
highlightText(text);
});
function highlightText(text){
let regexGreen = new RegExp(greenListArray.join('[,!?.]?|'), "ig");
let regexBlue = new RegExp(blueListArray.join('[,!?.]?|') + "ig");
let newText = text.replace(regexGreen, "<span class='green'>$&</span>")
.replace(regexBlue, "<span class='blue'>$&</span>");
$('#results').html(newText);
}
.blue{
background-color: red;
font: red;
}
.green{
background-color: green;
}
.greyHighlight:hover{
background-color: grey;
color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myform">
<fieldset>
<textarea name='textEntered' id='textEntered' />This is a cool story.</textarea>
<button type='submit' class="bttn">Enter</button>
</fieldset>
</form>
<div class="results-container"> <span class="results-title">Highlighted Text:</span> <div id="results"> </div> <br> </div>
<div class="wantedResults">
Results I wish to have <br>
<span class="blue">This is a</span><span class="green">cool story</span>
</div>
答案 0 :(得分:0)
我认为这可以满足您的需求。不过,这并不是理想的选择,因为如果存在<span>
或</span>
的多层结构,它将无法正常工作,但是在您的示例中确实可以产生正确的结果。希望这会有所帮助:)
let greenListArray = ["cool story"];
let blueListArray = ['This is a cool'];
$("#myform").submit(function(event){
event.preventDefault();
$('#results').html('');
let text = $('textarea#textEntered').val();
highlightText(text);
});
function highlightText(text){
// this replaces all spaces with regex that will allow the capturing of html tags '<>'
// note that I am only doing this for the first element in the array, this would need to loop over the elements if so desired...
greenListArray[0] = greenListArray[0].replace(new RegExp(' ', 'g'), '( |<.*>| <.*>|<.*> )');
blueListArray[0] = blueListArray[0].replace(new RegExp(' ', 'g'), '( |<.*>| <.*>|<.*> )');
let regexGreen = new RegExp(greenListArray.join('[,!?.]?|'), "ig");
let regexBlue = new RegExp(blueListArray.join('[,!?.]?|'), "ig");
text = replaceStuffs(text, regexGreen, 'green');
text = replaceStuffs(text, regexBlue, 'blue');
$('#results').html(text);
}
function replaceStuffs(text, regex, classToAdd) {
let matchRegex = regex.exec(text);
let needToAppend = true;
matchRegex = matchRegex[0]; // grab the matching string... as it seems to always be the first element in the array returned by .exec...
let replacement = matchRegex;
if (matchRegex.indexOf('<span') !== -1 && matchRegex.indexOf('</span>') !== -1) // there is a beginning and ending span tag... we leave it alone
{
}
else if (matchRegex.indexOf('<span') !== -1 && matchRegex.indexOf('</span>') === -1) // there's a beginning tag. we need to find the ending of that tag, and then append our ending </span>
{
let regexTemp = new RegExp('<span.*', "ig"); // lets select as much of this beginning tag as we can, so it'll hopefully be unique.
let str = regexTemp.exec(matchRegex);
// debugger; <-- this pauses Chrome's execution of JS. useful for testing...
str = str[0];
regexTemp = new RegExp(str+'.*</span>', "ig"); // use the string we found, look for the closing </span>
text = text.replace(regexTemp, '$&</span>'); // we have now put our closing span after the closing </span> that we found.
needToAppend = false; // set a variable so we don't append the </span> again later...
}
else if (matchRegex.indexOf('</span>') !== -1) // closing span, no beginning tag... we need to move it...
{
replacement = matchRegex.replace('</span>','');
replacement += '</span>';
}
replacement = '<span class="'+classToAdd+'">'+replacement+(needToAppend ? '</span>' : '');
text = text.replace(matchRegex, replacement);
return text;
}
.blue{
background-color: red;
font: red;
}
.green{
background-color: green;
}
.greyHighlight:hover{
background-color: grey;
color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myform">
<fieldset>
<textarea name='textEntered' id='textEntered' />This is a cool story.</textarea>
<button type='submit' class="bttn">Enter</button>
</fieldset>
</form>
<div class="results-container"> <span class="results-title">Highlighted Text:</span> <div id="results"> </div> <br> </div>
<div class="wantedResults">
Results I wish to have <br>
<span class="blue">This is a</span><span class="green">cool story</span>
</div>
答案 1 :(得分:0)
这可能与“这很酷”和“很酷的故事”重叠有关吗?
您可能过度编写了一个搜索,尤其是因为您要进行另一个搜索...
可能会在搜索中包括</span>
,例如
this is a cool(</span>)?
要么
cool(</span>)? story
答案 2 :(得分:0)
这适用于基本实现。重叠超过2次将无法正常工作。并且还需要处理空格。
var arr = [
{str:"cool story",
color: "green"},
{str:"This is a cool",
color: "blue"},
{str:"two best friends",
color: "red"},
{str:"about two best",
color: "yellow"},
];
$("#myform").submit(function(event){
event.preventDefault();
$('#results').html('');
let text = $('textarea#textEntered').val();
highlightText(text);
});
function highlightText(text)
{
for(var index=0;index<arr.length;index++)
{
var matches=text.match(arr[index].str.split(" ").join("\\s*(<.*>)*\\s*"));
if(matches)
{
for(var i=1;i<matches.length;i++)
{
if(!matches[i]) continue;
if(matches[i].indexOf("/")==-1)
{
text = text.replace(matches[0],matches[0].replace(matches[i],"")+matches[i]);
}
else
{
text = text.replace(matches[0],matches[i]+matches[0].replace(matches[i],""));
}
}
}
text = text.replace(arr[index].str, "<span class='"+arr[index].color+"'>$&</span>");
}
$('#results').append($(text))
}
.blue{
background-color: blue;
}
.green{
background-color: green;
}
.red{
background-color: red;
}
.yellow{
background-color: yellow;
}
.grey{
background-color: grey;
}
.greyHighlight:hover{
background-color: grey;
color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myform">
<fieldset>
<textarea name='textEntered' id='textEntered'>This is a cool story about two best friends.</textarea>
<button type='submit' class="bttn">Enter</button>
</fieldset>
</form>
<div class="results-container"> <span class="results-title">Highlighted Text:</span> <div id="results"> </div> <br> </div>
<div class="wantedResults">
Results I wish to have <br>
<span class="blue">This is a</span><span class="green">cool story</span>
</div>