简体   繁体   中英

Javascript count length specific string

i have a problem when count length with spesific string ;

basically, i have a string that store at variable.

something like this :

var x = "<p class='test'>one</p>
         <p class='test'>two</p>
         <p class='test'>three</p>
         <p class='test'>four</p>";

var count = x.length // expected 4 as result

how to accompolished this thing?

thanks in advance

Use regex String.match(new RegExp()).length

var x =  "<p class='test'>one</p>" + 
         "<p class='test'>two</p>" + 
         "<p class='test'>three</p>" +
         "<p class='test'>four</p>";

x.match(new RegExp("<p", "g") || []).length //4
//or count </p>
x.match(new RegExp("</p>", "g") || []).length //4
//or old 2009 answer
(x.split("<p").length - 1) //4

You are storing the data as a string and strings don't care what the characters are, they just see it all. If you want to be able to store the strings that make up paragraph elements and know how many of those you've made, you need an array of strings, like this:

 var x = []; x.push("<p class='test'>one</p>"); x.push("<p class='test'>two</p>"); x.push("<p class='test'>three</p>"); x.push("<p class='test'>four</p>"); alert(x.length); // 4 x.push("<p class='test'>five</p>"); alert(x.length); // 5

Another alternative is to create a div from your string and count the child elements.

var x = '<p class="test">one</p>'+
        '<p class="test">two</p>'+
        '<p class="test">three</p>'+
        '<p class="test">four</p>';

var div = document.createElement('div');
div.innerHTML = x;
var count = div.childNodes.length;

alert(count);

https://jsfiddle.net/dttz64qn/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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