Javascript: Special character in a javascript object property string. - javascript

I have a variable with some object/properties and I need to add a trademark to one of them. Is this possible?
var something = {
name: "This is trademarked",
//some more objects
};
I tried applying it this way:
var trademark = document.write("\u2122");
var something = {
name: "This is trademarked" + trademark,
//some more objects
};
But shows as undefined.

var something = {
name: "This is trademarked",
//some more objects
};
var trademark = "\u2122";
something.name += trademark;
// this is just to show the result, don't used it in a real case
document.write(something.name)

Eduardo's solution got me to the solution that worked for me in case anyone else views this in the future.
var trademark = "\u2122";
var something {
name: "some text " + trademark,
//more object
}

Related

Best ways to transform a text on an html page

I need to replace some words on an HTML page with links, i.e. "linkify" these words. I have an array of identifier descriptors, like this:
var symbols_desc = [
{
id: 'id_one',
name: 'struct my_struct_one',
},
{
id: 'id_two',
name: 'my_name_two',
},
/* ... */
]
So in certain areas of HTML page I need to transform all occurrences of struct my_struct_one to struct my_struct_one, etc.
I'm not an expert in the Web field, so, I use probably the dumbest way: I update HTML by means of jQuery. Like this:
$(document).ready(function() {
$(".some-class1, .some-class2").each(function() {
var o = $(this);
symbols_desc.forEach(function(desc){
o.html(
o.html().replace(
new RegExp('(\\b' + desc.name + '\\b)', 'g'),
'<a class="symb-link" href="#' + desc.id + '">$1</a>'
)
);
});
});
});
It works, but it is unacceptably slow. There are about 70 identifiers, HTML page is about 200 KB, and it takes about 5 seconds.
Given the complexity and awesomeness of some Web applications that I use from time to time, I'm sure there should be better ways to perform this simple task. I'd be glad to hear your suggestions.
In your case I think all we have do is to change comfortable forEach to simple for and use more variables, so please try:
$(".some-class1, .some-class2").each(function() {
var html = $(this).html();
for (var i = 0; i < symbols_desc.length; i++) {
html.replace(
new RegExp('(\\b' + symbols_desc[i].name + '\\b)', 'g'),
'<a class="symb-link" href="#' + symbols_desc[i].id + '">$1</a>'
);
}
$(this).html(html);
});
First off, no need to use jQuery. It probably contributes to slowing everything down. Get your HTML areas by using
var fooElements = document.querySelectorAll('.someclass1, .someclass2')
This returns a nodelist, and array like object, that can be looped using a normal for.
Also, your dictionary doesn't have to be an array.
var symbols_desc = {
'id_one' : 'struct my_struct_one',
'id_two' : 'my_name_two'
}
Now we can have one regex to replace everything in one go per html element you want to work on, instead of looping n * m times
var fooRegex = new RegExp(Object.keys(symbols_desc).join("|"),"gi");
All that remains is to do the actual work
for(var i = 0; i < fooElements.length; i++){
fooElements[i].innerHTML = fooElements[i].innerHTML.replace(fooRegex,function(matchedString){
return mapObj[matchedString.toLowerCase()];
});
}
Working example, it should be pretty fast:
var dictionary = {
'mouse': 'cat',
'dog': 'mouse',
'horse': 'dog',
'cat': 'horse'
}
var fooElements = document.querySelectorAll('.some-class1, .some-class2');
var fooRegex = new RegExp(Object.keys(dictionary).join("|"), "gi");
for (var i = 0; i < fooElements.length; i++) {
fooElements[i].innerHTML = fooElements[i].innerHTML.replace(fooRegex, function(matchedString) {
return dictionary[matchedString.toLowerCase()];
});
}
<div class="some-class1">
Dog, cat, mouse
</div>
<div class="some-class2">
Horse, cat, dog
</div>

How to retrieve string stored inside a variable?

I have a variable params inside a function someFunction(),
function someFunction() {
var params = ""
params += "type=" + type + "&intro=" + intro + "&val=" + val; // then I add a value on params
console.log(params.val); // now, how can i do this?
}
Any ideas?
Better to write your custom function.
Here what I have tried.
window.onload = function() {
var params = "";
var type = "types";
var intro = "int";
var val = "values";
params += "type=" + type + "&intro=" + intro + "&val=" + val;
var convertToObject = function(strParams) {
var objQueryString = {};
var arrParam = strParams.split('&');
console.log(arrParam)
arrParam.forEach(function(value, key) {
var arrKyValue = value.split('=');
objQueryString[arrKyValue[0]] = arrKyValue[1];
})
return objQueryString;
}
objParams = convertToObject(params);
console.log(objParams.val, objParams["val"])
}
Here is Plunker
When it's a string, it's a string. You could parse it to get values based on known format, but there is no way of referencing something inside of the string.
Therefore, it's better to store params in the object for later use and create a string only when you need it, based on that object.
So, it could be like this:
var params = {
val: val,
type: type,
intro: intro
};
then, params.val will be accessible. When you'll need a string, you'd do var string = "type=" + params.type + "&intro=" + params.intro + "&val=" + params.val;
Your params variable is just a string. What you are trying to do is access it like an object.
A better solution would be:
// Create an object
var params = {};
// Create the properties
params.type = "some type";
params.val = "some value";
params.intro = "some intro";
// Alternatively
var params = {
type: "some type",
val: "some value",
intro: "some intro"
};
// Function that does something with your params
function doSomething(input) {
console.log(input.val);
}
// Function that converts your object to a query string
function toQueryString(input) {
var keyValuePairs = [];
for (var key in input) {
if (input.hasOwnProperty(key)) {
keyValuePairs.push(encodeURI(key) + "=" + encodeURI(input[key]));
}
}
return keyValuePairs.join("&");
}
doSomething(params);
console.log(toQueryString(params));
Outputs
some value
type=some%20type&val=some%20value&intro=some%20intro
As a side note, it is generally a bad idea to use words that can be potentially a keyword in your code or in the future (IE: params). A better name would be one that is informative, such as welcomeMessage, introduction or employee (Based off the 3 values you listed)
var params = "" is not a function, its a statement. A function in JS is created by using function(params) = {} or in ES6 you can use =>. When you use += on a sting you are saying "take whatever string is already in params and add on to it what Im about to tell you." After your statement is evaluated you have a new string. Although strings can be accessed like arrays e.g. x = 'hello' and then x[0] would return 'h' where 0 refers to the character at the index of the string. You are trying to use dot notation which is used for JS object literals e.g. x = {prop1: 200, prop2: 300} then x.prop1 would return 200. Or using the array syntax you would do x[prop1] instead.
Do it this way, check demo - fiddle:
var value = false, temp;
params.split('&').forEach( function(item) {
temp = item.split('=');
if(temp[0] === 'val') {
value = temp[1];
}
})
console.log(value);

Jquery post a Array

I am having a Array which is generated by my Javascript in run time.
once that array is full with all the values I want to send it using POST to the server.
How can I do that ...
Pseudo code:
for(i=0;i<result.data.length;i++)
{
result.data[i].id
}
$.post("receiver.php", { xxxxx }, function(data){ console.log(data);});
How can I get that xxxx updated in the post
I checked the documentation in jquery but they are expecting to give all the values in POST.I do not want to do that.
Also, I want to send post only once so that traffic will be less.
EDIT
You can use join() to get all your array values converted to a string, using some char to separate it.
EDIT 2: As Kumar said he was using 2 arrays
var idsArray;
var namesArray;
for(i=0;i<result.data.length;i++)
{
idsArray[] = result.data[i].id;
namesArray[] = result.data[i].name;
}
var ids = idsArray.join(",");
var names = namesArray.join(",");
$.post("receiver.php", { ids:ids, names:names }, function(data){ console.log(data);});
similar to iBlue's comment, You can just send an object with post; you don't have to define the object in the post function, { } are simply the delimiters to define objects, which are similar to PHP associative arrays:
$.post('reciever.php', myData, function(data){ /*callback*/ });
The only thing is that you setup myData as an object like follows:
myData = {
0: 'info',
1: 'info'
}
//or even something like this
myData = {
someProp: 'info',
someProp2: {
anotherProp: 'moreInfo'
}
}
you can also use non-numerical indexes with objects, and easily add properties:
myData[2] = 'info';
or you can loop through it, just in a slightly different way:
for(i in myData){
myData[i]; //Do something with myArr[i]
}
the for in loop will also loop through non-numerical properties. And you can still get the length of myData by
myData.length;
EDIT:
Instead of sending a string:
IDs = {}
Names = {}
for(var i = 0; i < result.data.length; i++){
IDs[i] = result.data[i].id;
Names[i] = result.data[i].name;
}
$.post('reciever.php', {IDs: IDs, Names: Names}, function(data){});
In the PHP file you would access them like so
$_POST['IDs'][0] = "some id";
$_POST['Names'][0] = "some name";
EDIT:
Actaully I think the indexes are sent as strings, so might have to do
$_POST['IDs']['0']
Not sure, but it seems like you want to do this:
var sendObj = {};
for (var i=0; i<result.data.length; i++) {
var id = result.data[i].id,
name = result.data[i].name; // or some similiar computation
sendObj[name] = id;
}
$.post("receiver.php", sendObj, function(data){ console.log(data);});
This will send the result.data as name=id-value-pairs.

Referencing complex variables in JavaScript

How do you make the following JS variable references:
When you have an array (x[0], x[1], ...), and you have a button like so:
<button onclick="say(0)"></button>
The function looks like this:
function say(src){
// Define the box (some random div element will do)
var box = document.querySelector('#box');
// This is wrong, I know... I need to refer to the variable 'response[0]' in this case...
box.innerHTML = response[src];
}
When you have the following list of variables:
var book = "Some Book";
var shelf = "Some Shelf"
var bookshelf = "The cake!"
In this case, if I want to (for whatever reason) refer to the variable bookshelf, how do I do it by combining the variable names of the other two variables?
I mean, I can't do var x = book + shelf; since that will give me the result = "Some BookSome Shelf".
Don't make them variables, make them properties of an object:
var tags = {
book: 'Some book',
shelf: 'Some shelf',
bookshelf: 'The Cake!'
};
var which = 'bookshelf';
var x = tags[which];
You'll probably want to make them properties of an object (although they're probably already properties of the window object):
var stuff = {
book: "Some book!",
shelf: "Some shelf",
bookshelf: "The cake!"
};
function say(src) {
// Define the box (some random div element will do)
var box = document.querySelector('#box');
box.innerHTML = stuff[response[src]];
}

How can I print javascript objects?

I have an object
var object= {}
I put some data in the object and then I want to print it like this
document.write(object.term);
the term is a variable that changes depending on different situations. When I try printing this it comes up with undefined.
How would it be done?
Update:
this is the code I am dealing with. I guess it probably isn't the same as what I said above because I am doing it in selenium with browsermob, I just thought it would be similar to document.write(). Here is the code
var numCardsStr = selenium.getText("//div[#id='set-middle']/div[2]/h2");
var numCards = numCardsStr.substr(4,2);
browserMob.log(numCards);
var flash = {}
for(i=0; i<(numCards); i++){
var terms = selenium.getText("//div[#id='words-normal']/table/tbody/tr[" + (i + 2) + "]/td[1]");
var defs = selenium.getText("//div[#id='words-normal']/table/tbody/tr[" + (i + 2) + "]/td[2]");
flash[terms] = defs;
browserMob.log(flash.terms);
}
EDIT: You're using two different variable names, flash and flashcards. I don't know if they are meant to be the same thing, but you are setting the value using the [] notation, then getting it using . notation.
Try:
var flash = {};
...
flash[terms] = defs;
browserMob.log(flash[terms]);
If term is a variable to represent the property you are retrieving, then you should use the square bracket notation for getting the property from the object.
Example: http://jsfiddle.net/xbMjc/ (uses alerts instead of document.write)
var object= {};
object.someProperty = 'some value';
var term = "someProperty";
document.write( object[term] ); // will output 'some value'
If you're using document.write(), there's a good chance you are trying to reference the object before it's been instantiated. My advice: don't use document.write() unless you need it in a template. For all other purposes, wait till the page loads and then run your script as an event handler.
There could be other reasons for the failure, but your code sample isn't complete enough for a diagnosis.
To output the whole object as text, use a JSON library:
<script type="text/javascript" src="http://www.JSON.org/json2.js"></script>
.
var o = { "term": "value" };
document.write(JSON.stringify(o, null, 4));
This will output the object as a string and indent 4 spaces to make it easy to read.
What you do is this:
var terms = "abcd";
var defs = "1234";
var flash = {};
flash[terms] = defs;
This creates this object:
{
"abcd": "1234"
}
If you want to go through the properties (i.e. "abce"), do this:
for (var key in flash) {
document.write('Key "' + key + '" has value "' + flash[key] + '"<br/>');
}
This will output:
Key "abcd" has value "1234"
Because I haven't seen this mentioned yet:
var a = {prop1:Math.random(), prop2:'lol'};
a.toString = function() {
output = [];
for(var name in this) if(this.hasOwnProperty(name) && name != 'toString') {
output.push([name, this[name]].join(':'));
}
return "{\n"+output.join(",\n\t")+"\n}";
};
document.write(a);
// should look like:
/*
{
prop1:0.12134432,
prop2:lol
}
*/
In the case that you're defining an object class, like MyObj:
var MyObj = function(id) {
this.someIdentity = id;
};
MyObj.prototype.toString = function() {
return '<MyObject:'+this.someIdentity+'>';
};
And then anytime you write something like
document.write(new MyObject(2));
It'll appear as <MyObject: 2>.
Avoid document.write
If you use Firefox, install firebug and use it's console api
The same console apis should work in chrome too.
For IE, get companion js
In javascript, obj.propertyname is used if the property name is known before hand. If it's not, then:
if pn contains the property name, obj[pn] should give you the value.
Well in firefox and in Chrome/Safari you could simply use...
var myObj = {id: 1, name: 'Some Name'};
window.console.log(myObj);
And the console will output something like "Object"
If you are in Chrome you could inspect the internal values of the object with ease using the built in developer console.
If you use firefox the output should come out of firebug as well...
I'm stating this as an alternative of using document.write as it seems a little bit invasive to me to output content on the document...

Categories

Resources