Regex with javascript to extract content from a loop

It seems simple, but I never made a regex, so just a question from JS regex experts.

var str = '<a href="test">luckyy1</a> born on october 21, 1986 <a href="test">sdf2</a> born on september 22, 1985 <a href="test">erere</a> born on November 23, 1984 '; 

I got the values ​​successfully: luckyy1 , sdf2 , erere

But I need it like luckyy1+october+21+1986,sdf2+september+22+1985,erere+ ... and so on (maybe I need a regular expression ???)

Any help would be appreciated.

+3
source share
5 answers

Try the following:

 str = $("<div/>").html(str).text(); str = str.replace(/,?/g, '').replace(/born on?/g, '').split(' ').join('+') 

Demo

+1
source

While I recommend not parsing HTML with regex , it's simple enough, you have to do this.

"test"\s*>(.+?\d{4})

This will write something after the tag "test"> and end with 4 numbers (year in your example).

Your information is limited to a space in group 1. After that, I recommend breaking it up into spaces so that your individual elements can play.

Play with regex .

0
source

Basically, do you want to remove html tags?

Try:

 var StrippedString = OriginalString.replace(/(<([^>]+)>)/ig,""); 

from http://css-tricks.com/snippets/javascript/strip-html-tags-in-javascript/

If you want to get separate rows for each dom element (as your example shows), you can alternately move the DOM elements with jQuery and separate them separately.

EDIT:

Something like that:

 var $s = jQuery( the_string ); var result = []; $s.each(function(i, item){ result.push( $(item).text().replace(/(<([^>]+)>)/ig,"") ); }); 
0
source

Strictly with the markup you provided, you can do something like this:

 var values = $('<div><a href="test">luckyy1</a> born on october 21, '+ '1986 <a href="test">sdf2</a> born on september 22, 1985 ' + '<a href="test">erere</a> born on November 23, 1984</div>') .contents() .map(function(){ return $(this).text().replace('born on', '').trim(); }).get(); console.log(values); // ["luckyy1", "october 21, 1986", "sdf2", "september 22, 1985", "erere", "November 23, 1984"] 

The only thing I changed was added to the div line. Then you can use values.join('+') to concat with + , and replace the string in the space.

 values.join('+').replace(/\s/g, '+'); // to make all whitespace `+` 
0
source

This is a dirty decision, but somehow it can help you ...

 var str = '<a href="test">luckyy1</a> born on october 21, 1986 <a href="test">sdf2</a> born on september 22, 1985 <a href="test">erere</a> born on November 23, 1984 '; var r= /<a[^>]*>(.*)<\/a> born on ([\w]*) ([\d]*), ([\d]*) <a[^>]*>(.*)<\/a> born on ([\w]*) ([\d]*), ([\d]*) <a[^>]*>(.*)<\/a> born on ([\w]*) ([\d]*), ([\d]*)/; r.exec(str).splice(1).join('+'); 
0
source

All Articles