Sireini
Sireini

Reputation: 4262

Get part of string after a specific value

I try to get a part of a string this is the string:

"#" id="fs_facebook-btn" data-count="facebook" onclick="window.open('https://www.facebook.com/sharer/sharer.php?u=http%3A%2F%2Fsharebtns.fingerspitz.nl.ebox%2F', '_blank', 'scrollbars=0, resizable=1, menubar=0, left=100, top=100, width=550, height=440, toolbar=0, status=0');return false" title="Share on Facebook"

I would like to get the data-count value this is what I tried:

for (var i = 0; i < s.length; i++) {
    console.log(s[i]);
    console.log(s[i].substring(0, s[i].indexOf('data-count="')));
}

but then it stops at the part I want to get how can I achieve it to get the value of data-count?

Upvotes: 0

Views: 49

Answers (2)

fdomn-m
fdomn-m

Reputation: 28621

To continue using your method of .indexOf and .substring:

var s = '"#" id="fs_facebook-btn" data-count="facebook" onclick=...';

var searchFor = 'data-count="';

var startPos = s.indexOf(searchFor) + searchFor.length;  // add on the length to get the end
var endPos = s.indexOf('"', startPos);        // find the next " after data-count=

alert(s.substring(startPos, endPos));         // extract the string


An alternate would be to let jquery parse the html for you, even though it starts as a string, you can convert it to a jquery object by wrapping in <div .. >, eg:

var s = '"#" id="fs_facebook-btn" data-count="facebook" onclick=...';
alert($("<div " + s + "></div>").data("count"))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

while slightly less code, it will be slower if you have lots (10,000+) strings to parse.

Upvotes: 1

hsz
hsz

Reputation: 152294

You can try with splitting this string by whitespace, then finding proper element with find and cleaning it up with replace:

s.split(' ').find(v => v.contains('data-count')).replace(/.*?"([^"]+")/, '$1')

or at the end split by = and remove " characters:

s.split(' ').find(v => v.contains('data-count')).split('=')[1].replace(/"/g, '')

Upvotes: 0

Related Questions