当单击表中的值时,我将字符串添加到文本区域。必须能够选择和取消选择表中的值,并且它们将从文本区域添加/删除自身。文本区域必须是字符串,并且添加的值不能包含在任何其他字符中。
要添加的值可能包含任何字符,并且可能将其他值之一作为子字符串,以下是一些示例:HOLE 1
、HOLE 11
、孔 17
、孔 (1)
、剖切
、切入
、离开
、剪切
、评论员(史密斯、约翰)
、(目标)
、目标
将值附加到文本区域后,再次单击以取消选择它,我将搜索该值并将其删除,如下所示:
var regex = new RegExp("(?![ .,]|^)?(" + mySelectedText + ")(?=[., ]|$)", 'g');
var newDescriptionText = myTextAreaText.replace(regex, '');
正则表达式正确匹配文本的字符串/子字符串,例如然而,cutaway
和 away
不适用于以括号开头的任何内容,例如(目标)
。将单词边界选择器添加到表达式 \b
的开头,将使正则表达式匹配以括号开头的字符串,但不适用于包含相同文本的字符串/子字符串。
有没有办法使用正则表达式来实现这一点?或者其他方法?
这是一个正在运行的 CodePen example从表中添加/删除。
最佳答案
您可以使用字边界 (\b
) 来避免取消选择 away
并在列表中包含 cutaway
时出现问题。只需将正则表达式更改为:
regex = new RegExp("(?![ .,]|^)?(\\b" + cellText + "\\b)(?=[., ]|$)", 'g');
^^^ ^^^
这是我为使其正常工作而更改的代码:
removeFromDescription = function(cell) {
cell.classList.remove(activeClass);
// Remove from the active cells arry
var itemIndex = tempAnnotation.activeCells.indexOf(cell.textContent);
tempAnnotation.activeCells.splice(itemIndex, 1);
// Do the regex find/replace
var annotationBoxText = annotation.value,
cellText = regexEscape(cell.textContent), // Escape any funky characters from the string
regex = new RegExp("(^| )" + cellText + "( |$)", 'g');
var newDescription = annotationBoxText.replace(regex, ' ');
setAnnotationBoxValue(newDescription);
console.info('cellText: ', cellText);
console.info('annotationBoxText:', annotationBoxText);
console.info('newDescription: ', newDescription);
};
regexEscape = function(s) {
return s.replace(/([-\/\\^$*+?.()|[\]{}])/g, `\\$&`);
};
setAnnotationBoxValue = function(newValue) {
annotation.value = newValue;
};
关于javascript - 正则表达式仅匹配字符串,而不匹配子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43469107/