javascript - 换行不包含在单词中的字符

标签 javascript jquery html

我目前正在开发一个包含游戏制作者教程的网站。有时我不得不在网站上放几行代码。为了让它看起来更像 Game maker 本身,我想更改文本中特定字符和单词的颜色。

现在我正在尝试更改所有 X 和 Y 的颜色。这是我现在拥有的:

$(document).ready(function(){
    $(".code").children().each(function() {
        $(this).html($(this).html().replace(/\x\b/g, "<font color=red>x</font>"));
        $(this).html($(this).html().replace(/\X\b/g, "<font color=red>X</font>"));
        $(this).html($(this).html().replace(/\y\b/g, "<font color=red>y</font>"));
        $(this).html($(this).html().replace(/\Y\b/g, "<font color=red>Y</font>"));
    });
})

虽然它确实为字符着色,但它也为单词中的字符着色,这不是我想要的。我应该添加或更改什么,以便它只会为不在单词中的 X 和 Y 着色?

最佳答案

我认为这些代码可以解决您的问题。刚刚开始使用 \b 用于正则表达式

$(document).ready(function(){
    $(".code").children().each(function() {
        $(this).html($(this).html().replace(/\b\x\b/g, "<font color=red>x</font>"));
        $(this).html($(this).html().replace(/\b\X\b/g, "<font color=red>X</font>"));
        $(this).html($(this).html().replace(/\b\y\b/g, "<font color=red>y</font>"));
        $(this).html($(this).html().replace(/\b\Y\b/g, "<font color=red>Y</font>"));
    });
});

http://jsfiddle.net/fno9d6wz/

关于javascript - 换行不包含在单词中的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34768531/

相关文章:

javascript - 使用 Angular.JS 设置 <select> 的默认值

javascript - Font Awesome CSS 伪元素

html - CSS 库(例如 :Bootstrap) that supports IE6?

javascript - 如何使用 useRef react hook 关注列表项

javascript - ||创建 jQuery 插件时在 JavaScript 中使用(或运算符)

javascript - 如何使用 jquery 处理状态码 307 重定向

jquery - 对完整日历提出自己的看法

css - 单击空 <a> 标记时停止页面跳回顶部

javascript - 无法立即在弹出窗口内立即创建 'press' 刚刚创建的按钮。我必须关闭弹出窗口,然后再次打开它(chrome-extension 弹出窗口)

javascript - 创建具有悬停效果的响应式图像映射