Detect text language using JavaScript

Detect text language using JavaScript

Using language API from a third party, we can detect the string or text language in JavaScript.

In this Blog Post, I am using Lingvanex for the language detection.

Sample JavaScript Code:

const options = {
	method: 'POST',
	headers: {
		accept: 'application/json',
		'content-type': 'application/json',
		Authorization: '<AUTHORIZATION_KEY>'
	},
	body: JSON.stringify({
		q: 'bonjour'
	})
};

fetch(
	'https://api-gl.lingvanex.com/language/translate/v2/detect',
	options
)
.then(res => res.json())
.then(res => {
	console.log(
		JSON.stringify(res)
	);
	const obj = JSON.parse(
	        JSON.stringify( res )
        );
	let textLanguage = obj.data.detections[0][0].language;
	console.log(
		'textLanguage is',
		textLanguage
	);
})
.catch( err => console.error( err ) );

Output:

textLanguage is fr

Leave a Reply