Replace string value with javascript object - javascript

I am currently making a small module for NodeJs. For which I need a small help.
I will tell it like this.
I have a variable with string. It contains a string html value. Now I need to replace $(title) something like this with my object { "title" : "my title" }. This can be expanded to anything with user provide. This is current code.I think that I need RegEx for do this. Can you guys help me with this?
var html = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document $(title)</title>
</head>
<body>
<h1>Test file, $(text)</h1>
</body>
</html>`;
function replacer(html, replace) {
// i need a regex to replace these data
//return replacedData;
}
replacer(html, { "title" : "my title", "text" : "text is this" });

You can use a simple template function using regex,
var replacer = function(tpl, data) {
var re = /\$\(([^\)]+)?\)/g, match;
while(match = re.exec(tpl)) {
tpl = tpl.replace(match[0], data[match[1]])
re.lastIndex = 0;
}
return tpl;
}
use like
var result = replacer(html, { "title" : "my title", "text" : "text is this" });
jsfiddle
detail here
EDIT
Actually as torazaburo mentioned in the comment, it can be refactored as
var replacer = function(tpl, data) {
return tpl.replace(/\$\(([^\)]+)?\)/g, function($1, $2) { return data[$2]; });
}
jsfiddle
hope this helps

This solution uses template strings to do everything you want.
This solution has the advantage that, in contrast to the naive roll-your-own regexp-based template replacement strategy as proposed in another answer, it supports arbitrary calculations, as in
replacer("My name is ${name.toUpperCase()}", {name: "Bob"});
In this version of replacer, we use new Function to create a function which takes the object properties as parameters, and returns the template passed in evaluated as a template string. Then we invoke that function with the values of the object properties.
function replacer(template, obj) {
var keys = Object.keys(obj);
var func = Function(...keys, "return `" + template + "`;");
return func(...keys.map(k => obj[k]));
}
We define the template using ${} for substitutions (instead of $()), but escaping as \${ to prevent evaluation. (We could also just specify it as a regular string literal, but would then lose multi-line capability).
var html = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document \${title}</title> <!-- escape $ -->
</head>
<body>
<h1>Test file, \${text}</h1> <!-- escape $ -->
</body>
</html>`;
Now things work exactly as you want:
replacer(html, { "title" : "my title", "text" : "text is this" });
Simple example:
> replacer("My name is ${name}", {name: "Bob"})
< "My name is Bob"
Here's an example of calculated fields:
> replacer("My name is ${name.toUpperCase()}", {name: "Bob"})
< "My name is BOB"
or even
> replacer("My name is ${last ? lastName : firstName}",
{lastName: "Jones", firstName: "Bob", last: true})
< "My name is Jones"

Since you are using ES6 template string you can use a feature called 'tagged template strings'. Using tagged template strings you are allowed to modify the output of a template string. You create tagged template string by putting a 'tag' in front of the template string, the 'tag' is a reference to a method that will receive the string parts in a list as the first argument and the interpolation values as remaining arguments. The MDN page on template strings already provides an example template string 'tag' that we can use:
function template(strings, ...keys) {
return (function(...values) {
var dict = values[values.length - 1] || {};
var result = [strings[0]];
keys.forEach(function(key, i) {
var value = Number.isInteger(key) ? values[key] : dict[key];
result.push(value, strings[i + 1]);
});
return result.join('');
});
}
You use the 'tag' by calling:
var tagged = template`<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document ${'title'}</title>
</head>
<body>
<h1>Test file, ${'text'}</h1>
</body>
</html>`;
Notice that interpolation of variables uses the syntax ${'key'} instead of $(key). You can now call the produced function to get the desired result:
tagged({ "title" : "my title", "text" : "text is this" });
Run the code example on es6console

var binddingData=function(id,data){
var me=this,
arr=[];
arr=getControlBindding(id);
arr.forEach(function(node){
var content=getBinddingContent(node.getAttribute('DataTemp'),data);
binddingToHtml(node,content);
})
}
var getControlBindding=function(id){
var me=this;
return document.querySelectorAll('[DataTemp]');
}
var getBinddingContent=function(temp,data){
var me=this,
res='',
hasNull=false;
if(temp==null||typeof temp=='undefined'){
return res;
}
res= temp.replace(/\$\{([^\}]+)?\}/g, function($1, $2) {
if(data[$2]==null||typeof data[$2]=='undefined'){
hasNull=true;
}
return data[$2];
});
return hasNull?'':res;
}
var binddingToHtml=function(node,content){
var me=this;
if(node.getAttribute('IsDateTime')){
node.innerText='';//if u want change it to datetime string
return;
}
if(node.getAttribute('AddBr') && content==''){
node.innerText='';
var brTag=document.createElement('br');
node.appendChild(brTag);
return;
}
node.innerText=content;
}
You use the 'tag' by calling:
<div DataTemp="${d1}"></div>
<div DataTemp="${d2}"></div>
<div DataTemp="${d3}"></div>
<div DataTemp="${d3}+ +${d1}"></div>
<div DataTemp="${d3}/${d1}"></div>
<div DataTemp="${d4}\${d1}"></div>
<div DataTemp="(${d5}\${d1})"></div>
<div DataTemp="(${d3}\${d1})"></div>
with data var data={d1:'t1',d2:'t2',d3:'t3'}

Related

HTML encoding/decoding issue, when using JS to get from JSON data sample

I have a website and want to display text. The text is in German and comes from a JSON data set I have. This is retrieved from a localhost API URL for now. The German words have the special characters replaced with HTML encoded ones. For example, erzählt is saved in the JSON data as erz&#228hlt. When I make the textContent of my paragraph tag to the JSON German text, the HTML encoding does not work. It does work however if I just copy and paste it manually in. How can I trigger the encoding to work and have it show correctly?
Code:
Gets random German word from JSON API, puts text into paragraph. Encoding issue.
erz&#228hlt is shown instead of erzählt .
JSON example:
{ "id": "32", "ename": "Smile.", "gname": "L&#228cheln!" }
<head>
<meta http-equiv="Content-Type" content="text/html" charset="utf-8"/>
</head>
<h4>German:</h4>
<div>
<p id="gname">
</div>
<script>
const api_url = 'http://localhost:3000/fyp/api/grandom.php';
async function getData() {
const repsonse = await fetch(api_url);
const data = await repsonse.json();
var i = Math.floor((Math.random() * 16534) + 0);
const { gname, ename } = data[i];
document.getElementById('gname').textContent = gname;
document.getElementById('ename').textContent = ename;
}
getData();
</script>
Any help or advice appreciated. If anything needs explaining please let me know.
If your string contains HTML entities like &#228 then it isn’t text, it is HTML.
textContent expects you to pass plain text to it, not HTML source code.
Use innerHTML instead.
const value = "erz&#228hlt";
text.textContent = value;
html.innerHTML = value;
<div id=text></div>
<div id=html></div>
use innerHTML instead of innetText to solve your problem
function getData() {
const data = { "id": "32", "ename": "Smile.", "gname": "L&#228cheln!" };
document.getElementById('gname').innerHTML = data.gname;
document.getElementById('ename').innerHTML = data.ename;
}
getData();
<head>
<meta http-equiv="Content-Type" content="text/html" charset="utf-8"/>
</head>
<body>
<h4>German:</h4>
<div>
<p id="gname"></p>
<p id="ename"></p>
</div>
<body>

Display key name with spaces in ng-repeat

repeat where i am repeating key value pairs, I am having key without spaces where i need to display with space.
my ng-repeat:
ng-repeat="(key, value) in scenariosViewAll.collectionBookObject"
i am displaying in span:
<span class="accordion-title">
{{key}}
</span>
in controller i am pushing the array as :
vm.shared.collectionFlyoutObject.BusinessDrivers.push(data);
Its working fine and displaying key as BusinessDrivers.
But i need to display as Business Drivers .
You might be able to somehow work with the current key and add spaces to it the way you want. One alternative would be to just maintain state in the collection book object for the human readable form of the key. Assuming such a field keyView existed, then you would access it on the value, not the key, using this:
<span class="accordion-title">
{{value.keyView}}
</span>
Another approach would be to just maintain a map in your controller which can map the keys to the human readable forms you want, e.g.
$scope.keyViews = { };
$scope.keyViews['BusinessDrivers'] = 'Business Drivers';
And then display using this:
<span class="accordion-title">
{{keyViews[key]}}
</span>
But this approach is less nice than keeping all the relevant state in a single map, for maintenance and other reasons.
var app = angular.module('myApp', []);
app.filter('myFormat', function() {
return function(x) {
var txt = x.replace(/([A-Z]+)/g, "$1").replace(/([A-Z][a-z])/g, " $1")
return txt;
};
});
we can make a filter to create the effect.
in template
<span class="accordion-title">
{{key | myFormat}}
</span>
You can use a custom function to split camelCase. You just have to define the function in your main controller and it can be referenced anywhere in your code.
var app = angular.module('plunker', []);
app.controller('ApplicationController', function($scope) {
$scope.splitCamelCase = function(input) {
if (!input)
return;
var j = 0;
var splitString = "";
var i = 0;
for (i = 1; i < input.length; i++) {
if (input.charAt(i) == input.charAt(i).toUpperCase()) {
splitString = splitString + " " + input.slice(j, i);
j = i;
}
}
splitString = splitString + " " + input.slice(j, i);
return splitString.replace("And", "and").replace("and", " and").substr(1, splitString.length);
};
});
<!doctype html>
<html ng-app="plunker">
<head>
<meta charset="utf-8">
<title>AngularJS Plunker</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.js"></script>
</head>
<body>
<div class="container" ng-controller="ApplicationController">
<div class="row">
{{splitCamelCase("BusinessDrivers")}}
</div>
</div>
</body>
</html>
I am copied the snippet from #Vivz to make my change
try this.
var app = angular.module('plunker', []);
app.controller('ApplicationController', function($scope) {
$scope.splitCamelCase = function(input) {
return input.replace(/([A-Z]+)/g, " $1").replace(/([A-Z][a-z])/g, " $1");
};
});
<!doctype html>
<html ng-app="plunker">
<head>
<meta charset="utf-8">
<title>AngularJS Plunker</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.js"></script>
</head>
<body>
<div class="container" ng-controller="ApplicationController">
<div class="row">
{{splitCamelCase("BusinessDrivers")}}
</div>
</div>
</body>
</html>
If you only want to convert the key from camelCase to a space separated proper string, then I suggest you to use a filter as that would be the easiest way.
You can simply create a new filter and use that.
controller:
var myApp = angular.module('myApp',[]);
myApp.filter('splitCamelCase', function() {
return function(input) {
return input.charAt(0).toUpperCase() + input.substr(1).replace(/[A-Z]/g, ' $&');
}
});
View:
<div ng-controller="MyCtrl">
{{str | splitCamelCase }}
</div>
This is just an example. Hope this helps :) Fiddle
I think the answers above is a little bit overwhelming. It can all be narrowed down to :
.filter('splitByUppercase', function() {
return function(input) {
return input.split(/(?=[A-Z])/).join(' ')
}
})
Example
<span ng-repeat="t in test">
{{ t | splitByUppercase }}<br>
</span>
http://plnkr.co/edit/OUfmusiswNeEpSURFVRx?p=preview
If you want to lowercase the extracted words so it becomes "Business drivers" etc you can use
.filter('splitByUppercase', function() {
return function(input) {
input = input.split(/(?=[A-Z])/);
input = input.map(function(s,i) {
if (i>0) s = s[0].toLowerCase() + s.substring(1)
return s
});
return input.join(' ')
}
})

Internationalization of HTML pages for my Google Chrome Extension

I found a very easy way to implement translation (or localization) of my Google Chrome Extension, but that seems to apply only to .json, css and js files.
But how to localize my html content, say in the popup or an options window?
What you would do is this.
First, in your HTML use the same syntax as Chrome requires anywhere else. So your basic popup.html will be:
<!DOCTYPE html>
<html>
<head>
<title>__MSG_app_title__</title>
</head>
<body>
__MSG_link001__
<!-- Need to call our JS to do the localization -->
<script src="popup.js"></script>
</body>
</html>
Then provide the usual translation in _locales\en\messages.json:
{
"app_title": {
"message": "MyApp",
"description": "Name of the extension"
},
"link001": {
"message": "My link",
"description": "Link name for the page"
},
"prompt001": {
"message": "Click this link",
"description": "User prompt for the link"
}
}
And finally your popup.js will perform the actual localization:
function localizeHtmlPage()
{
//Localize by replacing __MSG_***__ meta tags
var objects = document.getElementsByTagName('html');
for (var j = 0; j < objects.length; j++)
{
var obj = objects[j];
var valStrH = obj.innerHTML.toString();
var valNewH = valStrH.replace(/__MSG_(\w+)__/g, function(match, v1)
{
return v1 ? chrome.i18n.getMessage(v1) : "";
});
if(valNewH != valStrH)
{
obj.innerHTML = valNewH;
}
}
}
localizeHtmlPage();
Plain an simple:
{
"exmaple_key": {
"message": "example_translation"
}
}
<sometag data-locale="example_key">fallback text</sometag>
document.querySelectorAll('[data-locale]').forEach(elem => {
elem.innerText = chrome.i18n.getMessage(elem.dataset.locale)
})
Building from ahmd0's answer. Use a data attribute to allow a hard-coded fallback.
<!DOCTYPE html>
<html>
<head>
<title data-localize="__MSG_app_title__">My Default Title</title>
</head>
<body>
Default link text
<script src="localize.js"></script>
</body>
</html>
Then provide the usual translation in _locales\en\messages.json:
{
"app_title": {
"message": "MyApp",
"description": "Name of the extension"
},
"link001": {
"message": "My link",
"description": "Link name for the page"
},
"prompt001": {
"message": "Click this link",
"description": "User prompt for the link"
}
}
And finally your localize.js will perform the actual localization:
function replace_i18n(obj, tag) {
var msg = tag.replace(/__MSG_(\w+)__/g, function(match, v1) {
return v1 ? chrome.i18n.getMessage(v1) : '';
});
if(msg != tag) obj.innerHTML = msg;
}
function localizeHtmlPage() {
// Localize using __MSG_***__ data tags
var data = document.querySelectorAll('[data-localize]');
for (var i in data) if (data.hasOwnProperty(i)) {
var obj = data[i];
var tag = obj.getAttribute('data-localize').toString();
replace_i18n(obj, tag);
}
// Localize everything else by replacing all __MSG_***__ tags
var page = document.getElementsByTagName('html');
for (var j = 0; j < page.length; j++) {
var obj = page[j];
var tag = obj.innerHTML.toString();
replace_i18n(obj, tag);
}
}
localizeHtmlPage();
The hard-coded fallback avoids the i18n tags being visible while the JavaScript does the replacements. Hard-coding seems to negate the idea of internationalisation, but until Chrome supports i18n use directly in HTML we need to use JavaScript.
As RobW noted in a comment, a feature request for adding i18n support in HTML using the same mechanism was created, but it has since then been rejected due to performance and security concerns. Therefore you can't use the same approach.
The issue mentions one possible workaround: to have separate HTML pages per language and switch between them in the manifest:
"browser_action": {
"default_popup": "__MSG_browser_action_page__"
}
But if that's not a suitable approach, the only way is to translate the page dynamically via JavaScript. You mention a solution the simplest approach, by just tagging elements to translate with ids and replacing them on page load.
You can also employ more sophisticated tools like webL10n in parallel with Chrome's approach. Note that you should probably still minimally implement Chrome's approach, so that Web Store knows that the item is supporting several languages.
Rather than parsing the full DOM, just add a class "localize" to the elements that have to be translated and add a data attribute data-localize="open_dashboard"
<div class="localize" data-localize="open_dashboard" >
Open Dashboard
</div>
JavaScript :
$('.localize').each(function(index,item){
var localizeKey = $(item).data( 'localize' );
$(item).html(chrome.i18n.getMessage(localizeKey));
});
'_locales/en/messages.json' file
{
"open_dashboard": {
"message": "Open Dashboard",
"description": "Opens the app dashboard"
}
}
A workaround to avoid replacements:
Use a simple "redirect"
It works for popups and options
In your manifest, declare the default popup
"default_popup": "popup/redirect.html"
The popup/redirect.html is almost empty. It just includes the script link to the redirect script
<!DOCTYPE html>
<html>
<head></head>
<body>
<script src="redirect.js"></script>
</body>
The popup/redirect.js file is very simple too:
var currentlang = chrome.i18n.getMessage("lang");
var popupUrl = chrome.runtime.getURL("popup/popup-"+currentlang+".html");
window.location.href = popupUrl;
Create multiple popups, already localized:
popup-fr.html
popup-en.html
Go into each of your messages.json files (in _locales) and add a "lang" message with the current language abbreviation as value: en for the english json, fr in the french json...
example for _locales/en/message.json:
"lang": {
"message": "en",
"description": "Locale language of the extension."
},
A simple workaround for very small project... definitely not a good choice for large ones. And it also works for Option pages.
One of the ways to localize your content in popup html is to fetch it from javascript onLoad. Store the strings in the _locales folder under various languages supported by you as mentioned here and do chrome.i18n.getMessage("messagename") to fetch and load the variable strings and set them using javascript/jquery onLoad function for each html element from your background.js or whatever js you load before your html pages loads.
I faced the same problem, but I solved it with a simple approach using custom data attributes.
Implement a localizing class that uses chrome.i18n and call it in the DOMContentLoaded event. In HTML, mark up the element you want to localize with the data-chrome-i18n attribute. (This attribute name is tentatively named.) Specifying the message name as the value of this attribute localizes the text content of the element. If you want to localize an attribute, specify it in the format attribute_name=message_name. Multiple specifications can be specified by separating them with ;.
const i18n = (window.browser || window.chrome || {}).i18n || { getMessage: () => undefined };
class Localizer {
constructor(options = {}) {
const { translate = Localizer.defaultTranslate, attributeName = Localizer.defaultAttributeName, parse = Localizer.defaultParse } = options;
this.translate = translate;
this.attributeName = attributeName;
this.parse = parse;
}
localizeElement(element) {
for (const [destination, name] of this.parse(element.getAttribute(this.attributeName))) {
if (!name)
continue;
const message = this.translate(name) || '';
if (!destination) {
element.textContent = message;
}
else {
element.setAttribute(destination, message);
}
}
}
localize(target = window.document) {
const nodes = target instanceof NodeList ? target : target.querySelectorAll(`[${CSS.escape(this.attributeName)}]`);
for (const node of nodes)
this.localizeElement(node);
}
}
Localizer.defaultTranslate = i18n.getMessage;
Localizer.defaultAttributeName = 'data-chrome-i18n';
Localizer.defaultParse = (value) => {
return (value || '').split(';').map(text => (text.includes('=') ? text.split('=') : ['', text]));
};
const localizer = new Localizer();
window.addEventListener('DOMContentLoaded', () => {
localizer.localize();
});
<!DOCTYPE html>
<html data-chrome-i18n="lang=##ui_locale">
<head>
<meta charset="UTF-8" />
<title data-chrome-i18n="extensionName"></title>
</head>
<body>
<p data-chrome-i18n="foo;title=bar;lang=##ui_locale"></p>
</body>
</html>
There are several things to consider to solve this problem.
Use chrome.i18n (Many people will want to aggregate in messages.json.)
Supports attributes as well as element content
Supports not only popup but also options page
Rendering performance
Security
First, the approach of switching HTML for each language in manifest.json does not work. Even if you give __MSG_*__ to the default_popup field, popup will still show the error "ERR_FILE_NOT_FOUND". I don't know why. There is no detailed reference to default_popup in the Chrome extensions Developer Guide, but MDN mentions that it is a localizable property. Similarly, if you give __MSG _*__ to the page field in options_ui, the extension itself will fail to load.
I intuitively felt that the approach of replacing __MSG_*__ in HTML and rewriting the result usinginnerHTML had performance and security problems.
This answer is cool!
And I want to make some modifications.
For chrome 93.0.4577.63 chrome.i18n.getMessage permalink, link-by-version
chrome.i18n.getMessage(messageName, substitutions, {escapeLt})
So I want to make it support
substitutions
escapeLt
Test Data
// _locales/en/messages.json
{
"hello": {
"message": "<b>Hello</b> $USER$ Welcoming $OUR_SITE$. $EMOJI$",
"description": "Greet the user",
"placeholders": {
"user": {
"content": "$1", // chrome.i18n.getMessage("hello", "variable 1")
"example": "Carson"
},
"our_site": {
"content": "Example.com"
},
"emoji": {
"content": "$2",
"example": "\uD83D\uDE42" // 🙂, 😎
}
}
},
"app": {
"message": "My cool APP.",
"description": "description"
}
}
<!-- test.html-->
<script src="my-i18n.js"></script>
<p data-i18n="__MSG_hello__"></p>
<p data-i18n="__MSG_hello__<b>Carson</b>"></p>
<p data-i18n="__MSG_hello__<b>Carson</b>|0"></p>
<p data-i18n="__MSG_hello__<i>Carson</i>|1"></p>
<button title="__MSG_hello__<b>Carson</b>" data-i18n></button>
<button title="__MSG_hello__<b>Carson</b>|0" data-i18n></button>
<button title="__MSG_hello__<b>Carson</b>|1" data-i18n></button>
<p title="__MSG_app__" data-i18n="__MSG_hello__Carson,🙂"></p>
output
Script
// my-i18n.js
/**
* #param {string} msg "__MSG_Hello__para1,para2|1" or "__MSG_Hello__para1,para2|0"
* */
function convertMsgAsFuncPara(msg) {
const match = /__MSG_(?<id>\w+)__(?<para>[^|]*)?(\|(?<escapeLt>[01]{1}))?/g.exec(msg) // https://regex101.com/r/OeXezc/1/
if (match) {
let {groups: {id, para, escapeLt}} = match
para = para ?? ""
escapeLt = escapeLt ?? false
return [id, para.split(","), Boolean(Number(escapeLt))]
}
return [undefined]
}
function InitI18nNode() {
const msgNodeArray = document.querySelectorAll(`[data-i18n]`)
msgNodeArray.forEach(msgNode => {
const [id, paraArray, escapeLt] = convertMsgAsFuncPara(msgNode.getAttribute("data-i18n"))
if (id) {
msgNode.innerHTML = chrome.i18n.getMessage(id, paraArray, {escapeLt})
}
// ↓ handle attr
for (const attr of msgNode.attributes) {
const [attrName, attrValue] = [attr.nodeName, attr.nodeValue]
const [id, paraArray, escapeLt] = convertMsgAsFuncPara(attrValue)
if (!id) {
continue
}
msgNode.setAttribute(attrName, chrome.i18n.getMessage(id, paraArray, {escapeLt}))
}
})
}
(() => {
window.addEventListener("load", InitI18nNode, {once: true})
})()
Modify pseudo-category content in batches.
<div data-content="font"></div>
div::before {
content: attr(data-content);
}
document.querySelectorAll('[data-content]').forEach(el => {
el.dataset.content = chrome.i18n.getMessage(el.dataset.content);
});
Use CSS Internationalization.
<p></p>
p::before {
content: "__MSG_font__";
}
Another workaround - you can use content property in css with __MSG_myText inside.
Use Vue.js:
<html>
<head>
</head>
<body>
<div id="app">{{msgTranslated}}</div>
</body>
</html>
javascript file injected:
new Vue({
el: '#app',
data: {
msgTranslated: chrome.i18n.getMessage("message")
}
})

Determine the /category/ in the URL with Javascript

I have a need to include (through Javascript) different content depending on the major category captured from the url.
The website is laid out like so:
http://example.com/Category/Arts/Other/Sub/Categories/
http://example.com/Category/News/Other/Sub/Categories/
http://example.com/Category/Sports/Other/Sub/Categories/
http://example.com/Category/Business_And_Finance/Other/Sub/Categories/
The different major categories above are:
Arts, News, Sports, and Business_And_Finance
What is the best way to accomplish this in javascript.
What I need may look something like the following,
if (category = Arts) {
alert("Arts");
}else if (category = News) {
alert("News");
}...
Thank you in advance.
Split the location.href then do a switch on the appropriate variable. So, for example:
var url = document.location.href,
split = url.split("/");
/*
Split will resemble something like this:
["http:", "", "example.com", "Category", "Arts", "Other", "Sub", "Categories", ""]
So, you'll find the bit you're interested in at the 4th element in the array
*/
switch(split[4]){
case "Arts":
alert("I do say old chap");
break;
case "News":
alert("Anything interesting on?");
break;
default:
alert("I have no idea what page you're on :O!");
}
you can access the current url like this
document.location.href
you could do a
if ( document.location.href.indexOf("categoryYouWant")>-1){
//whatever you want
}
but you should do a regular expression
category=document.location.href.match(/example\.com\/(\w+)\//i)[1];
var url = window.location.href;
var category = url.split('Category/')[1].split('/')[0];
if (category === 'Arts') {
alert("Arts");
}else if (category === 'News') {
alert("News");
}
I made this example:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<script type="text/javascript">
function determine(url)
{
var myArray = url.split('/');
if(myArray[4] == "News")
alert(myArray[4]);
}
</script>
</head>
<body>
<div>
http://example.com/Category/News/Other/Sub/Categories/
</div>
</body>
</html>
Saludos ;)

JavaScript to read content between <a> tags

Below is my html page:
<html>
<head>
<title>My Cat website</title>
</head>
<script type="text/javascript" src="script12.js"></script>
<body>
<h1>
My_first_cat_website
</h1>
</body>
</html>
Below is my JavaScript:
window.onload=initall;
function initall()
{
var ans=document.getElementsByTagName('a')[0].firstChild.data;
alert(ans);
if(ans<10)
{
alert(ans);
}
var newans=ans.subString(0,9)+"...";
}
Here my code is not going into if block. My requirement is if var "ans" length is above 10 then append it with ... else throw an alert directly. Can anyone help me?
Here is Solution using data property
window.onload=initall;
function initall()
{
var ans=document.getElementsByTagName('a')[0].firstChild.data;
if(ans.length<10)
{
alert("hmmm.. its less then 10!");
}
var newans= ans.substring(0,9)+"...";
document.getElementsByTagName('a')[0].firstChild.data = newans;
}
Here is it live view you wise to check example: http://jsbin.com/obeleh
I have never heard of the data property on a DOM element. Thanks to you, I learned it's a property on textNode elements (the same as nodeValue).
Also, using getElementsByTagName when the ID is available is unperformant.
subString doesn't work, it is substring. The case is important for methods as javascript is case sensitive (like most programming languages).
The other thing you're missing is an else. In your code, the var newans... will always be ran.
Here is something working:
window.onload = function() {
var ans = document.getElementById( 'message' ).textContent;
if ( ans.length < 10 ) {
alert( ans );
}
else {
var newans = ans.substring( 0, 9 ) + '...';
}
}

Categories