【问题标题】:Using javascript to manipulate string into dom elements使用javascript将字符串操作成dom元素
【发布时间】:2012-11-18 03:40:58
【问题描述】:

我有一串动态填充的文本。在每个字符串中,都有一个常用词:“type”。给定一个存储为变量的字符串,我想使用 javascript 找到单词“type”并在它之前放置一个潜水,然后在字符串之后放置一个关闭 div。 像这样:

var string = "Here is some text that contains the word type and more text after";

我希望最终结果是这样的:

Here is some text that contains the word <div>type and more text after</div>

我该怎么办?

当前代码如下:

var wod = $("#wod a").attr("title");
    var newwod = wod.replace("Copyright 2012, GB Blanchard - Learn Spanish: www.braser.com","");
    //get ride of example and everythign after it
    var finalwod = newwod.split("Example")[0];
    var newstring = finalwod.replace(/(type.+)/,"<div>$1</div>");


   $("#wod span").append(newstring);

【问题讨论】:

  • 我会先写一些代码。如果它不起作用,请回到这里向我们展示您拥有的东西。
  • 如果“type”出现的次数更多怎么办?
  • 那么我们要抓取第一个字符串“type”

标签: javascript replace split


【解决方案1】:

这真的是唯一您可用的方式吗?

Asad 有一个很好的正则表达式示例,然而,他还指出您的方法不是最佳实践。

为什么你不能有一些结构?

var returnedData = { "type": "div", "text": "I like best practice" };
//Might need error checking in future
var newElement = document.createElement(returnedData.type);
newElement.innerHTML = returnedData.text;
$("#wod span").append(newElement);

【讨论】:

    【解决方案2】:

    只需使用replace:

    string = string.replace(/(type.+)/,"<div>$1</div>");
    

    请注意,当您尝试修改由比单个文本节点更复杂的结构组成的 HTML 时,这不是最佳方法,但它适用于这种特定情况。

    正如 Jack 所指出的,您不需要在这里使用捕获组,因为整个比赛已经可以使用 $&amp;

    string = string.replace(/type.+/,"<div>$&</div>");
    

    【讨论】:

    • 我刚刚添加了包含您的代码的代码。它没有按预期工作。对于单个文本节点来说,这只是一件快速的一次性事情
    • @JCHASE11 这是short example,您可以在其中看到它的工作原理。调试其余代码超出了原始问题的范围。
    • +1。删除了我的问题;您不需要内存捕获括号,而是可以在替换字符串中使用$&amp;
    • @Jack 我会将其编辑到我的答案中,感谢您指出这一点。
    猜你喜欢
    • 2014-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-26
    • 2012-12-02
    • 2016-10-20
    • 1970-01-01
    相关资源
    最近更新 更多