简体   繁体   English

javascript在字符串中找到div id并删除它的内容

[英]javascript find div id inside string and delete it's content

I have a string with some variable html saved inside, among which a div with static id="time", 我有一个字符串,里面保存了一些变量html ,其中一个div的静态id =“time”,

example: 例:

myString = "<div class="class">blahblah</div><div id="time">1:44</div>"

How can I create a new identical string cutting off only the time? 如何创建一个新的相同字符串,只切断时间? (1:44 in this case). (在这种情况下为1:44)。 I can't look for numbers or the ":" because is not safe in my situation. 我无法查找数字或“:”因为在我的情况下不安全。

What i've tried without success is this: 我没有成功的尝试是这样的:

  var content = divContainer.innerHTML;

  var jHtmlObject = jQuery(content);
  var editor = jQuery("<p>").append(jHtmlObject);
  var myDiv = editor.find("#time");
  myDiv.html() = '';
  content = editor.html();
  console.log('content -> '+content);

 var myString = '<div class="class">blahblah</div><div id="time">1:44</div>'; //create a dummy span //put the html in it //find the time //remove it's inner html //execute end() so the jQuery object selected returns to the span //console log the innerHTML of the span console.log($('<span>').html(myString).find('#time').html('').end().html()); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

You can achieve this using a regular expression in plain javascript like so: 你可以在普通的javascript中使用正则表达式实现这一点,如下所示:

myString.replace(/(<div id="time">).*(<\/div>)/, '$1$2')

If you want to extract only the 1:44 portion you can use the following: 如果您只想提取1:44部分,可以使用以下内容:

myString.match(/(<div id="time">)(.*)(<\/div>)/)[2]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM