String内的String内的变量 [英] Variable inside a String inside a String

查看:241
本文介绍了String内的String内的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试将变量放入已经在字符串内的字符串中时,我遇到了一个小问题。基本上,我试图用颜色变量(一个字符串,例如#FF0)来改变特定单词的颜色。这就是替换函数的样子:

I'm running into a little problem when I try to put a variable inside a string that's already inside a string. Basically, I'm trying to change the color of a specific word with a color variable (a string, e.g. "#FF0"). That's what the replace function looks like:

$('#textWithTheWord').replaceWith($('<div></div>').append($('#textWithTheWord').clone()).html().replace(word, '<span style="color:red;">' + word + '</span>'));

请注意,我想要替换中的红色< span使用该变量的style =color:red;>'
提前致谢!

Note that I want to replace the "red" in '<span style="color:red;">' with that variable. Thanks in advance!

推荐答案

一个简单的解决方案就是简单地替换 innerHTML 元素的属性由一个新的html字符串组成,该字符串将包含 span 中的单词。但是,它不是一个非常灵活的解决方案,因为通过替换 innerHTML 属性,所有元素都将被更新并且可能会产生意外结果,除非您定位仅包含文本的元素节点。

An easy solution would be to simply replace the innerHTML property of your element by a new html string that would have wrapped the words in a span. However, it's not a very flexible solution, since by replacing the innerHTML property, all the elements would be renewed and that might give unexpected results, unless you target elements that only holds text nodes.

假设正文包含此文本:

this is some text and I want to replace the word cool

你可以:

var $body = $(document.body);

$body.html($body.html().replace(/\b(cool)\b/g, '<span style="color: red;">$1</span>'));

这里 / \b(酷)\ b / g 正则表达式将匹配每个单词并在其上创建一个捕获组,允许我们在替换表达式中引用它作为 $ 1

Here the /\b(cool)\b/g regex will match every cool words and create a capturing group on them, allowing us to reference it in the replacement expression as $1.

然而,最先进的解决方案可能实现如下:

However, a most advanced solution could probably be implemented like:


  • 循环不包含在 span 中的文本节点,该节点具有数据样式文本属性。 (你可以检查 textNode.parentNode 属性)

  • <<<< span data-styled-text> 标记。请查看 https://developer.mozilla.org/fr/docs/DOM /Text.splitText

  • 查询所有< span data-styled-text> 元素并执行任何操作希望和他们在一起。

  • Loop over text nodes not contained within a span that has a data-styled-text attribute. (you could check the textNode.parentNode property)
  • Sourround the words that you want by a <span data-styled-text> tag. Have a look at https://developer.mozilla.org/fr/docs/DOM/Text.splitText
  • Query all the <span data-styled-text> elements and do whatever manipulation you want with them.

我玩弄了这个概念,我为你创造了一个小提琴,展示你如何操纵文字您希望使用 regex 来定位特定文本的任何方式。我创建了2个主要函数 wrapText styleText ,它们允许您使用页面上的文本执行任何操作。它可以进一步优化,但你会得到这个想法。

I have toyed around with that concept and I have create a fiddle for you that shows how you could manipulate text in any ways you want using a regex to target specific text. I have created 2 main functions wrapText and styleText that will allow you to do whatever you want with text on the page. It could be further optimzed, but you will get the idea.

看看 http://jsfiddle.net/scarsick/tX4Ge/1/

Have a look at http://jsfiddle.net/scarsick/tX4Ge/1/

以下函数允许您在文本节点中包装任何文本。

The following function allows you to wrap any text in a text node.

function wrapText(textNode, textRx, wrapFn) {
    var global = textRx.global,
        wrapEl,
        result, 
        rightTextNode,
        matchedText,
        index;

    while (result = textRx.exec(textNode.nodeValue)) {
        rightTextNode = textNode.splitText(index = result.index);
        rightTextNode.nodeValue = rightTextNode.nodeValue.substring((matchedText = result[0]).length);
        wrapEl = wrapFn(matchedText, index);
        wrapEl.appendChild(document.createTextNode(matchedText));
        rightTextNode.parentNode.insertBefore(wrapEl, rightTextNode);

        if (!global) {
            break;
        }

        textNode = rightTextNode;
        textRx.lastIndex = 0;
    }    
}

以下函数允许您设置其中包含的任何文本的样式一个元素。

The following function allow you to style any text contained within an element.

function styleText(el, textRx, styleFn) {
    var wrapEl = document.createElement('span'),
        slice = [].slice;

    wrapEl.setAttribute('data-styled-text', 'true');

    styleText = function(el, textRx, styleFn) {
        var childNodes = slice.call(el.childNodes, 0),
            i = 0,
            len = childNodes.length,
            node;

        for (; i < len; i++) {
            node = childNodes[i];

            switch (node.nodeType) {
                case 3:
                     if (!node.parentNode.getAttribute('data-styled-text')) {
                         wrapText(node, textRx, function (text, index) {
                             var el = wrapEl.cloneNode();

                             styleFn(el, text, index);

                             return el;
                         });

                         continue;
                    }

                    styleFn(node.parentNode);
                    break;
                case 1:
                    styleText(node, textRx, styleFn);
                    break;
            }
        }
    };

    styleText(el, textRx, styleFn);
}

这篇关于String内的String内的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆