使用javascript将字符串操作为dom元素

时间:2012-11-29 23:04:23

标签: javascript replace split

我有一串文字,是在动态填充的。在每个字符串中,有一个常用词:“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);

2 个答案:

答案 0 :(得分:4)

只需使用replace

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

请注意,当您尝试修改包含比单个文本节点更复杂的结构的HTML时,这不是最好的方法,但它会针对此特定情况执行此操作。

正如杰克指出的那样,你不需要在这里使用捕获组,因为整个匹配已经可以使用$&

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

答案 1 :(得分:0)

这真的是唯一的方式吗?

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