Count words in a string on Javascript, Typescript, and Php
Sometimes we may want to count how many words do exist on a specific text. Let's say we have a raw string that contains some arbitrary text, and we want to know how many words it contains.
Using the TurboCommons library this process is as simple as calling a method and getting its result.
You can play and test it online here
Counting words with the TurboCommons library
There's a general purpose countWords() method inside the StringUtils class which lets you count the number of words inside a string. It also allows you to specify which word separator character you want to use (normally the empty space). Let's see how to do it for different programming languages:
Count words in Php
Download the latest TurboCommons phar file from the downloads section, place it on your project as a dependency and run the following code:
require '%path-to-your-project-dependencies-folder%/turbocommons-php-X.X.X.phar';
use org\turbocommons\src\main\php\utils\StringUtils;
echo StringUtils::countWords('oneword')."<br>";
echo StringUtils::countWords('two words')."<br>";
echo StringUtils::countWords('three words here')."<br>";
The output of the previous code should be:
1
2
3
Count words in Javascript on a website
Download the latest turbocommons-es5.js file from the downloads section or use npm to add the dependecy to your project (npm install turbocommons-es5). Then run the following code:
<script src="turbocommons-es5/turbocommons-es5.js"></script>
<script>
var StringUtils = org_turbocommons.StringUtils;
console.log(StringUtils.countWords('oneword'));
console.log(StringUtils.countWords('two words'));
console.log(StringUtils.countWords('three words here'));
</script>
The console log for the previous code should be:
1
2
3
Count words in Typescript (TS)
The recommended way is to use npm to obtain the turbocommons dependency by executing the following command at the root of your project:
npm install turbocommons-ts
Or you can download the latest turbocommons-ts files from the downloads section and copy the dependency by yourself. Then run the following code:
import { StringUtils } from 'turbocommons-ts';
console.log(StringUtils.countWords('oneword'));
console.log(StringUtils.countWords('two words'));
console.log(StringUtils.countWords('three words here'));
The output of the previous code should be:
1
2
3
Count words in a NodeJs App
Install the dependency by executing the following command at the root of your project:
npm install turbocommons-ts
And then run the following code:
const {StringUtils} = require('turbocommons-ts');
console.log(StringUtils.countWords('oneword'));
console.log(StringUtils.countWords('two words'));
console.log(StringUtils.countWords('three words here'));
Which should output:
1
2
3