Click to See Complete Forum and Search --> : Character or substring count


emmanuellamy
05-29-2003, 03:29 AM
Hi everybody,
Does Javascript have a built-in function to search for, and return the count of a specific character or substring in a string? If not how can one approach the problem of extracting some substring starting from a certain point defined by the nth position of a specific character or substring within the string in question. For instance I want to extract a substring that would start after the third word in a string. To do that, I'd want my codes to calculate the position of the 3rd " " space character of the string. How do I do that? I couldn't find a way out with the indexOf and lastIndexOf methods. Thanks for any tip.

Emmanuel

AdamGundry
05-29-2003, 03:43 AM
You might be able to use something like this:
words = sentence.split(" ");

That gives an array, words, which has each word (text from sentence seperated by a space) as a single element. You can then iterate through the array elements, find the length, access each element via words[3], etc.

If that's not what you want, you might be able to use String.search() (http://devedge.netscape.com/library/manuals/2000/javascript/1.5/reference/string.html#1194332).

Adam

Gollum
05-29-2003, 03:55 AM
Or alternatively, you could use regular expressions.
e.g.

"the third word is word".match(/\S+/g)[2]

gives us the third word from the string - the \S matches anything that is not whitespace

emmanuellamy
05-29-2003, 03:57 AM
Hi Adam,
The way I understand it, the split method combined with the indexOf should do the trick. Let me give it a try. And I'll let you know. In the meantime, thanks a lot!

Emmanuel

emmanuellamy
05-29-2003, 04:25 AM
Hi Collum,
Thanks for the tip. It's not quite transparent to me. But I feel the logic behind it. So, I am going to take a closer look at the RegExp parameters and switches and I am sure I will get a better understanding of your suggestion. Thank you, man!

Emmanuel