2012-11-29 122 views
1

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

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); 
+1

我会写一些代码开始。当它不起作用时,回到这里并告诉我们你有什么。 –

+0

如果“类型”出现的次数更多,该怎么办? –

+0

然后我们要抓住第一个字符串“type” – JCHASE11

回答

4

只需使用replace

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

请注意,这不是当你试图修改HTML,它由多个复杂的最佳方法结构而不是单个文本节点,但它将适用于此特定情况。

正如杰克已经指出的那样,你不需要在这里使用捕获组,因为整场比赛使用$&已经可用。

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

我刚刚添加了我的代码,包括你的。它没有按预期工作。这对于单个文本节点来说只是一次快速的事情。 – JCHASE11

+0

@ JCHASE11下面是一个[简单示例](http://jsfiddle.net/KnAKG/),您可以在其中看到这个工作。调试其余代码超出了原始问题的范围。 –

+0

+1。删除了我的问题;您不需要内存捕获括号,而是可以在替换字符串中使用'$&'。 –

0

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

阿萨德有一个正则表达式的一个很好的例子,但是,他还指出,你的做法是不是最好的做法。

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

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);