-1

I have a html snippet like this stored in a variable for example

var parse= 'Hello<i class="emoji emoji_smile" title=":smile:"></i><i class="emoji emoji_angry" title=":angry:"></i>World'

Now I want to parse this html and it must grab the value of the title and replace the tag only with the title then return the result like this using javaScript or jQuery

var parsed = Hello:smile::angry:world

Can anyone point me towards right direction on how I can do it? So that I can work it out?

Stack learner
  • 1,726
  • 2
  • 11
  • 21

2 Answers2

1

You can do it using replace method with regexp:

var parse= 'Hello<i class="emoji emoji_smile" title=":smile:"></i><i class="emoji emoji_angry" title=":angry:"></i>World'

var result = parse.replace(/<i.*?title="(.*?)"><\/i>?/g, "$1");

console.log(result); //Hello:smile::angry:World

Here a working fiddle: https://jsfiddle.net/ste8s7eL/

JulCh
  • 2,710
  • 2
  • 19
  • 21
  • this works too thank you so much. Can you recommend some nice resource to learn regex for noobs? – Stack learner Apr 15 '16 at 14:30
  • This article is a good beginning: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp. I use this http://regexr.com/ too, very useful :) – JulCh Apr 15 '16 at 14:32
0

You could wrap it in a container and map it to join it. Well, that would give:

var parse= 'Hello<i class="emoji emoji_smile" title=":smile:"></i><i class="emoji emoji_angry" title=":angry:"></i>World';

var parsed = $('<div/>', {html:parse}).contents().map(function(){
   return this.title || this.nodeValue;
}).get().join('');

$('body').append(parsed);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
A. Wolff
  • 74,033
  • 9
  • 94
  • 155