[英]Replace string if the string is not part of a larger string using regex in javascript
I'm trying to write a function which would Uppercase some words in a textarea
but I'm having trouble, as these words could be part of other words and I only want to uppercase them when they are standing alone. 我正在尝试编写一个将
textarea
某些单词大写的函数,但是我遇到了麻烦,因为这些单词可能是其他单词的一部分,我只想在它们单独站立时将它们大写。
Eg: I want to uppercase OR
but only when not in a word like befORe
. 例如:我想大写
OR
但仅当不使用befORe
这样的词befORe
。 These words can however be written in a multitude of ways, like at the start of a line, between one or more whitespace
characters or in something like this: (somethingsomething)OR(somethingelse)
and probably even more, depending on the way other people write their query code. 但是,这些单词可以多种方式书写,例如在一行的开头,一个或多个
whitespace
字符之间,或诸如此类的东西:( (somethingsomething)OR(somethingelse)
,甚至可能更多,具体取决于其他人的方式写下他们的查询代码。
I had the idea of working with regex
, but I'm not skilled enough to work out every possibility of writing these words. 我有使用
regex
的想法,但是我不够熟练,无法找出编写这些单词的所有可能性。
I have no way of changing the textarea
to other, better plugins or editors as it's already part of a functioning script. 我无法将
textarea
更改为其他更好的插件或编辑器,因为它已经是功能脚本的一部分。
Any helpful idea would be greatly appreciated. 任何有用的想法将不胜感激。
EDIT: One additional question 编辑:另外一个问题
I got really helpful answers to my question, Thank you everyone. 我对我的问题有非常有帮助的答案,谢谢大家。 I do have an additional question though.
我还有一个额外的问题。 What if, other then checking that it's not part of a word, I also want to check that it's not preceded or followed by a
.
如果,然后再检查它是否不是单词的一部分,该怎么办呢?我还想检查它是否不在单词的前面或后面
.
period. 期。 I tried adding
(?!\\.)
at the beginning of it, but that doesN't work at all. 我尝试在其开头添加
(?!\\.)
,但这根本不起作用。 Is there a way to check for that as well? 有没有办法检查呢?
//EDIT: Never mind, I figured it out. //编辑:没关系,我知道了。 it's \\b(?!\\.)something(?!\\.)\\b for the check at the start and end of the word.
它是\\ b(?!\\。)something(?!\\。)\\ b,用来检查单词的开头和结尾。
Matching on a word boundary \\b
may suit: 在单词边界
\\b
上匹配可能适合:
'foo or bar'.replace(/\bor\b/, 'OR'); // foo OR bar
You can also provide a function to replace, so: 您还可以提供替换功能,因此:
'foo or bar'.replace(/\b(or)\b/, function(m){return m.toUpperCase()})); // foo OR bar
which might be good for cases where you have multiple possible matches: 如果您有多个可能的匹配项,那么这可能会很好:
'foo or bar and fum'.replace(/\b(or|and)\b/ig, function(m){return m.toUpperCase()}); // foo OR bar AND fum
Something like this? 像这样吗 ( °_• )
(°_•)
var txt="or some text or before (.)or(.) anywhere Or";
console.log(txt.replace(/\bor\b/gi,"OR"));
// "OR some text OR before (.)OR(.) anywhere OR"
像这样:
'(something)or(somethingelse) before or oR Or OR oreos thor'.replace([^\w]([oO][rR])[^\w], 'OR');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.