I have a symbol (#) seperated variable as shown below
var inputStr = "IceCreams#Cone";
How can i split this and form a string in java script variable .
With the above input String how can form a string as
Are You Sure to add a Category Under IceCreams => Cone
I have tried as shown below ,but couldn't achive that dynamically
Thanks in advance .
function myFunction(inputStr)
{
var res = inputStr.split('#');
var r = confirm("Are You Sure to add a Category Under" +res[0]+" "+res[1]+" );
if (r == true) {
} else {
}
}
http://jsfiddle.net/4km0k9nv/1/
You code works if you fix your typo.
window.onload = function() {
function myFunction(inputStr) {
var res = inputStr.split('#');
alert("Are You Sure to add a Category Under " + res[0] + " " + res[1] + " ?" );
}
myFunction("Ice#cream");
}
If you just want to replace the "#" symbol, you can use the string replace function.
var str = "part1#part2";
var str2 = str.replace('#', " => ");
Your example should work fine, but it seems to be a typo.
Good Luck
I was messing around with it and I came up with this. Is this what you want? It runs the function on the input element blur.
function myFunction(inputStr)
{
var res = inputStr.split('#');
confirm("Are You Sure to add a Category Under " + res[0] + " => " + res[1] + " ?");
}
<input type="text" onblur="myFunction(this.value)">
Hope this helps!
function myFunction(inputStr)
{
var res = inputStr.split('#');
var r = confirm("Are You Sure to add a Category Under " + res[0] + " => "+ res[1] + "?");
if (r == true) {
addNewCategory(res[0], res[1]); // rename/rewrite this call as needed
} else {
cancelAdd(); // replace this line with whatever you need.
}
}
Alternatively you can say:
var res = inputStr.replace("#", " => ");
var r = confirm("Are You Sure to add a Category Under " + res + "?");
The second bit of code would make res a string instead of an array of strings. Depending on your needs, that may suffice. If you'd like to or need to use res as an array of strings, then the first chunk of code should be all your need.
Related
I am having a string like this:
"welcome country !
and some texts
Keyword1:the value
keyword2: the value2"
I want to remove keyword on undo the corresponding checkbox and also its value using Javascript. Now i could remove the keyword while undo checkbox but not the value they have entered near the keyword.
I have tried substring functions and some other, but i couldn't fix it.
my code below:
$("#txtNote").val(url.replace($(this).attr("data-id") + ":", ""));
I just want to remove the texts immediately after the ":"
here is my entire code:
if ($(this).attr("data-selected1") == "true") {
$("#detailChronic").show();
$(this).attr("data-selected1", "false");
//$(".hjk").remove(":contains('" + $(this).attr("data-id") + "')");
var url = $.trim($("#txtNote").val());
str = $("#txtNote").val();
//var t = str.substring(str.indexOf(":"))
//alert(t);
//url = url.replace(/\s+/g, "\n");
// $("#txtNote").val(url.replace($(this).attr("data-id") + ":", ""));
// $("#txtNote").val(url.replace($(this).attr("data-id") + ":" + $(this).attr("data-id").value(), ""));
//url.replace($(this).attr("data-id") + ":", "");
alert(url);
var temp2 = temp1.replace(/($(this).attr("data-id"))(\:(.*))/, "");
alert(temp2);
var temp1 = url.replace($(this).attr("data-id"), "");
alert(temp1);
$("#txtNote").val(temp1);
// $("#txtNote").val(url.replace($(this).attr("data-id") + ":" + $(this).attr("data-id").value(), ""));
if ($("#selectedList").html() == "") {
$("#detailChronic").hide();
}
}
if you want to remove 'Keyword1:the value', then try
var keyWordToRemove = 'Keyword1';
var rgxStr = keyWordToRemove + ':[a-zA-Z0-9 ]*\n';
var rgx = new RegExp(rgxStr,'g');
var text = `welcome country !
and some texts
Keyword1:the value
keyword2: the value2`;
console.log(text);
text = text.replace(rgx,"");
console.log(text);
Hope it helps :)
You can try it using regex like this
var url = `welcome country !
and some texts
Keyword1:the value
keyword2: the value2`;
console.log(url.replace("Keyword1:", "test key "))
console.log(url.replace(/(Keyword1)(\:(.*))/, "$1 test value"))
you can replace Keyword1 with $(this).attr("data-id") + ":" in your code
I created a "custom append" function that taking in two parameters and appending their's value in a one line.
I need to make the first parameter's value to append in a gray color but the second value have to stay as it is.
I tried to use a "css(property, name)" function but it didn't work.
Where is my fallacy and how to get a needed result?
var showText = function(who, str) {
if (str !== "") {
var colorWho = who.name;
colorWho.css("color", "gray");
$("#storyBoard").append("<br>" + colorWho + ": " + str + "<br>");
var element = document.getElementById("storyBoard");
element.scrollTop = element.scrollHeight;
}
};
Here you go
Fiddle
CSS
p > span { /* If you're going to take this to a larger environment, you may want to use classes instead */
color:gray;
}
JS
var showText = function(who, str) {
if(str !== ""){
var colorWho = who.name;
$("#storyBoard").append("<p><span>"+colorWho + "</span>: " +str+ "<p>");
}
};
var obj = {
name : "Preacher",
}
showText(obj, "Is an awesome comic book !");
Is this what you require?
$("#storyBoard").append("<br><span style='color:gray;'>" + colorWho + "</span>: " + str + "<br>");
Okay, that title will sound a bit crazy. I have an object, which I build from a bunch of inputs (from the user). I set them according to their value received, but sometimes they are not set at all, which makes them null. What I really want to do, it make an item generator for WoW. The items can have multiple attributes, which all look the same to the user. Here is my example:
+3 Agility
+5 Stamina
+10 Dodge
In theory, that should just grab my object's property name and key value, then output it in the same fashion. However, how do I setup that if-statement?
Here is what my current if-statement MADNESS looks like:
if(property == "agility") {
text = "+" + text + " Agility";
}
if(property == "stamina") {
text = "+" + text + " Stamina";
}
if(property == "dodge") {
text = "+" + text + " Dodge";
}
You get that point right? In WoW there are A TON of attributes, so it would suck that I would have to create an if-statement for each, because there are simply too many. It's basically repeating itself, but still using the property name all the way. Here is what my JSFiddle looks like: http://jsfiddle.net/pm2328hx/ so you can play with it yourself. Thanks!
EDIT: Oh by the way, what I want to do is something like this:
if(property == "agility" || property == "stamina" || ....) {
text = "+" + text + " " + THE_ABOVE_VARIABLE_WHICH_IS_TRUE;
}
Which is hacky as well. I definitely don't want that.
if(['agility','stamina','dodge'].indexOf(property) !== -1){
text = "+" + text + " " + property;
}
If you need the first letter capitalized :
if(['agility','stamina','dodge'].indexOf(property) !== -1){
text = "+" + text + " " + property.charAt(0).toUpperCase() + property.substr(1);
}
UPDATE per comment:
If you already have an array of all the attributes somewhere, use that instead
var myatts = [
'agility',
'stamina',
'dodge'
];
if(myatts.indexOf(property) !== -1){
text = "+" + text + " " + property.charAt(0).toUpperCase() + property.substr(1);
}
UPDATE per next comment:
If you already have an object with the attributes as keys, you can use Object.keys(), but be sure to also employ hasOwnProperty
var item = {};
item.attribute = {
agility:100,
stamina:200,
dodge:300
};
var property = "agility";
var text = "";
if(Object.keys(item.attribute).indexOf(property) !== -1){
if(item.attribute.hasOwnProperty(property)){
text = "+" + text + " " + property.charAt(0).toUpperCase() + property.substr(1);
}
}
Fiddle: http://jsfiddle.net/trex005/rk9j10bx/
UPDATE to answer intended question instead of asked question
How do I expand the following object into following string? Note: the attributes are dynamic.
Object:
var item = {};
item.attribute = {
agility:100,
stamina:200,
dodge:300
};
String:
+ 100 Agility + 200 Stamina + 300 Dodge
Answer:
var text = "";
for(var property in item.attribute){
if(item.attribute.hasOwnProperty(property)){
if(text.length > 0) text += " ";
text += "+ " + item.attribute[property] + " " + property.charAt(0).toUpperCase() + property.substr(1);
}
}
It's unclear how you're getting these values an storing them internally - but assuming you store them in a hash table:
properties = { stamina: 10,
agility: 45,
...
}
Then you could display it something like this:
var text = '';
for (var key in properties) {
// use hasOwnProperty to filter out keys from the Object.prototype
if (h.hasOwnProperty(k)) {
text = text + ' ' h[k] + ' ' + k + '<br/>';
}
}
After chat, code came out as follows:
var item = {};
item.name = "Thunderfury";
item.rarity = "legendary";
item.itemLevel = 80;
item.equip = "Binds when picked up";
item.unique = "Unique";
item.itemType = "Sword";
item.speed = 1.90;
item.slot = "One-handed";
item.damage = "36 - 68";
item.dps = 27.59;
item.attributes = {
agility:100,
stamina:200,
dodge:300
};
item.durability = 130;
item.chanceOnHit = "Blasts your enemy with lightning, dealing 209 Nature damage and then jumping to additional nearby enemies. Each jump reduces that victim's Nature resistance by 17. Affects 5 targets. Your primary target is also consumed by a cyclone, slowing its attack speed by 20% for 12 sec.";
item.levelRequirement = 60;
function build() {
box = $('<div id="box">'); //builds in memory
for (var key in item) {
if (item.hasOwnProperty(key)) {
if (key === 'attributes') {
for (var k in item.attributes) {
if (item.attributes.hasOwnProperty(k)) {
box.append('<span class="' + k + '">+' + item.attributes[k] + ' ' + k + '</span>');
}
}
} else {
box.append('<span id="' + key + '" class="' + item[key] + '">' + item[key] + '</span>');
}
}
}
$("#box").replaceWith(box);
}
build();
http://jsfiddle.net/gp0qfwfr/5/
I want to have a user's input auto fill the punctuation of a phone number to look like this (xxx) xxx-xxxx. I have written an example jfiddle here but it breaks when filling in the last 4 digits of the phone number.
$("#phone").on("change keyup paste", function () {
var output;
var input = $("#phone").val();
input = input.replace(/[^0-9]/g, '');
var area = input.substr(0, 3);
var pre = input.substr(3, 4);
var tel = input.substr(6, 4);
if (area.length < 3) {
output = "(" + area;
} else if (area.length == 3 && pre.length < 3) {
output = "(" + area + ")" + " " + pre;
} else if (area.length == 3 && pre.length == 3) {
output = "(" + area + ")" + " " + pre + "-" + tel;
}
$("#phone").val(output);
});
HTMl:
<input id='phone'></input>
I realize this post is older but i found it quite useful and made some minor modifications to enhance it for all telephone fields and to allow for deleting characters if the user makes a mistake.
$("input[type='tel']").each(function(){
$(this).on("change keyup paste", function (e) {
var output,
$this = $(this),
input = $this.val();
if(e.keyCode != 8) {
input = input.replace(/[^0-9]/g, '');
var area = input.substr(0, 3);
var pre = input.substr(3, 3);
var tel = input.substr(6, 4);
if (area.length < 3) {
output = "(" + area;
} else if (area.length == 3 && pre.length < 3) {
output = "(" + area + ")" + " " + pre;
} else if (area.length == 3 && pre.length == 3) {
output = "(" + area + ")" + " " + pre + "-" + tel;
}
$this.val(output);
}
});
});
<input type="tel" placeholder="(XXX) XXX-XXXX" />
When you're getting the pre code from the number, you're trying to get the index of 4, instead of four digits. So change that, and it should start working:
var pre = input.substr(3, 3);
If you don't want the dynamic filling, the other posted answers might be useful.
Regular expressions are your friend.
var ok = phNum.search(/^\(?\d{3}\D*\d{3}\D*\d{4}$/);
if (ok==0) {
var parts = phNum.match(/^\(?(\d{3})\D*(\d{3})\D*(\d{4})$/);
output.value='('+parts[1]+') '+parts[2]+'-'+parts[3];
}
Accepts: 404-555-1234, 4045551234, (404) 555-1234, etc.
Returns: (404) 555-1234
If you started to use regexp, why dont you go whole way through. Below the code that filter input value and convert it to your look.
Beware, this code only for value that contains only digits. You could block any other types via plugins or your own code. (jquery.numeric plugin is a good choice)
jquery
$(document).on('change', '.js-phone-number', function() {
var
$this = $(this),
number = $this.val();
number = number.replace(/(\d{3})(\d{3})(\d{4})/, '($1)-$2-$3');
$this.val(number);
});
You are fetching variable pre as substring of length 4 and then checking it for it is less than or equal to 3. So, basically your last else if block will never be true.
Change var pre = input.substr(3,3);
Your code will work fine.
I am using prototype in my application but I am not sure how to add this correctly. Basically I have the following function and I need to construct the href of an anchor from which I already have the reference to a series of appended values
MyJavascriptClass.prototype.init = function() {
this.ToDate = $(this.Prefix + 'ToDate');
this.FromDate = $(this.Prefix + 'FromDate');
}
so in the following function I need to add those as parameters in the url attribute
MyJavascriptClass.prototype.btnClicked = function(evt) {
this.lnkShowLink.setAttribute('href', 'MyWebpage.aspx?StartDate=7/18/2012&EndDate=1/19/2012');
}
How can i do something like 'MyWebPage.aspx?StartDate=this.ToDate&EndDate=this.FromDate' ? Any help would be appreciated.
If you are using jquery, and $(this.Prefix + 'ToDate') and $(this.Prefix + 'FromDate') represent fields that contain values, then you can do this:
MyJavascriptClass.prototype.btnClicked = function(evt) {
this.lnkShowLink.setAttribute('href', 'MyWebpage.aspx?StartDate=' + this.ToDate.val() + '&EndDate=' + this.FromDate.val() + '');
}
It is difficult to tell from your code what they represent, and why you have them wrapped in $(..).
If ToDate and FromDate contain the two date values, then this should work...
'MyWebPage.aspx?StartDate=' + this.ToDate + '&EndDate=' + this.FromDate
If you don't know every properties:
var properties = [];
for(var i in this)
if(this.hasOwnProperty(i))
properties.push(i+'='+this[i]);
var url = 'MyWebPage.aspx?'+properties.join('&');
var string = "My name is: ",
name = "Bob",
punctuation = ".",
greeting = string + name + punctuation;
Or
var User = { name : "Bob", age : 32, sign : "Leo" },
welcome = "Hi, I'm " + User.name + ", and I'm " + User.age + " years old, I'm a " + User.sign + ", and I enjoy long walks on the beach.";