我如何 select 字符串的 javascript 部分,添加 html 标签或删除部分?

How do I select parts of a string with javascript, add html tag to that or delete parts?

我有一个段落,想要 select 以 ! 结尾的第一行或者 。或者 ?并给它一个 header 标签。

在段落末尾,我想 select 以 # 开头的单词并使它们消失。

<p>
  Lorem ipsum!
  Dolor sit amet, consectetuer adipiscing elit. Aenean 
  commodo ligula eget dolor. Aenean massa. Cum sociis natoque 
  penatibus et magnis dis parturient montes, nascetur ridiculus 
  mus. Donec quam felis. 
  #sociis #natoque #penatibus #magnis
</p>

应该是:

<p>
  <h1>Lorem ipsum!</h1>
  Dolor sit amet, consectetuer adipiscing elit. Aenean 
  commodo ligula eget dolor. Aenean massa. Cum sociis natoque 
  penatibus et magnis dis parturient montes, nascetur ridiculus 
  mus. Donec quam felis. 
</p>

这是我目前发现的: http://jsfiddle.net/3ZKP9/37/

已更新 工作 jsfiddle:http://jsfiddle.net/3ZKP9/105/

更新 2 处理所有段落 http://jsfiddle.net/florisvl/3ZKP9/192/

var myString = "!Hello!";
var coolioString = myString.replace("!", "<h1>")
var coolioString1 = coolioString.replace("!", "</h1>")
console.log(coolioString1)

像这样?

鉴于可变段落是您的 p 标签,这将满足您的需求。

// 1. Get the text
// Could also use p.innerText but node.data is faster.
var paragraph = document.getElementsByTagName('p')[0];
var text = paragraph.childNodes[0].data;

// 2. Remove all words starting with #
// By using 'g' in the reg exp it will replace 
// all matches not just the first
// This replaces words like ' #foo', and '#bar '
text = text.replace(/( #\w*)|(#\w* )/g, '');

// 3. Surround the first line ending 
// with a '.' or '!' or '?' with h1s
text = text.replace(/([^\n]*?[.!?])/, '<h1></h1>');

// 4. Update p
paragraph.innerHTML = text;

希望对你有所帮助