1

Here is my string

var str = 'varying<div class="desc_1"><div>Changing or xyz</div></div>';

And I want to extract "varying" and "Changing or xyz" word from sentence using regular expression in javascript. I want output like this

str1 = "varying";
str2 = "Changing or xyz";


Js Fiddle Link

4
  • Are you trying to parse html code? If not you are better off creating separate text nodes and div nodes, then make changes to you text nodes when needed. Commented Dec 18, 2014 at 16:21
  • i want to store this two separate string in json Commented Dec 18, 2014 at 16:22
  • You could try str.split(/<[^>]+>/).filter(function( txt ){ return txt != "" }) but seriously, don't use regular expressions to parse HTML. Commented Dec 18, 2014 at 16:36
  • Ohhk. Thanks. I'll use create element method. Commented Dec 18, 2014 at 16:42

1 Answer 1

3

Do you need to use a regular expression here?

var str = 'varying<div class="desc_1"><div>Changing or xyz</div></div>';
var tmp = document.createElement('div');
tmp.innerHTML = '<div>' + str + '</div>';

var text = [];

var divs = tmp.getElementsByTagName('div');
for (var i = 0; i < divs.length; i++) {
  var textEle = divs[i].childNodes[0];
  if (textEle.nodeValue !== null) {
    text.push(textEle.nodeValue);
  }
}

console.log(text);
document.getElementById('output').innerHTML = text.join(', ');
<p id="output"></p>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.