tags:

views:

48

answers:

4

Hi all, Could someone please tell me how to find the occurence of a character in a string? I have to check the number of lines getting displayed (using the br tag) in a dynamically created div. Thanks in advance, Ashriya

A: 

string.indexOf('c')

pinichi
I tried this indexOf() but it doesn't seem to work..:(
Ashriya
I have to display some cities in the div. I bind these from the database, so I use the br tag to display them one by one. How can I check the no of cities getting displayed dynamically?
Ashriya
+1  A: 

You could try

JavaScript indexOf() Method

or maybe use split and array length.

astander
I tried this indexOf() but it doesn't seem to work..:(
Ashriya
I have to display some cities in the div. I bind these from the database, so I use the br tag to display them one by one. How can I check the no of cities getting displayed dynamically?
Ashriya
A: 

SPLIT can be a good option as suggested by @astander

You can use Regular expression as well

import java.util.regex.Matcher; 
import java.util.regex.Pattern; 

public class javaRE { 
    public static void main(String[] args) { 

    String message = "Your contents";

    Pattern p = Pattern.compile("your character");
    Matcher matcher = p.matcher(message); 

    int count=0;
    while(matcher.find()&& matcher.group() != null){
        count++;
    }
    } 
}

Above code will help you to know the occurence of any character of substring or other pattern.

Best way

string.lastIndexOf('a');
articlestack
java, javascript - same thing, who cares :P
Anurag
@articlestack, I tried ur method but I don't understand what the "Pattern" and "Matcher" do. Could u help me with that please? Thanks.
Ashriya
articlestack
A: 

You can use split and get the length of the array:

var div = document.getElementById('div');
alert(div.innerHTML.split(/\<br\s*\/\>/).length;

The /\<br\s*\/*\>/ is a Regular Expression that looks for all <br/>, <br />

Mic
Mic, thanks for ur reply. Will try this one.
Ashriya
Hey Mic, since the /* is used for comments, its not working..:(
Ashriya
Remove it and use only `/\<br\s*\/\>/`
Mic