Need to Replace by JavaScript - javascript

Need to Replace by jquery.
MY Json is:
var money={"money1":"957.06","money2":"1,368,737.85"}
Need to get result:
var money={"money1":"957.06","money2":"1368737.85"}
var res = money.replace(/,/, "");
by this its replaceing all the ","how to slove this?

You first need to iterate thru every value and then replace in it:
var money={"money1":"957.06","money2":"1368737.85"}
$.each( money, function( key, value ) {
value = value .replace(/,/, "");
});

use JavaScript replace()
e.g.:
money.money2 = money.money2.replace(/,/g, "");
http://www.w3schools.com/jsref/jsref_replace.asp

Add a g (global) flag to your regex; otherwise, only the first match will be replaced. Also, you need to access the actual properties of money that contain values:
money.money1 = normalizeMoney(money.money1);
money.money2 = normalizeMoney(money.money2);
function normalizeMoney(str) {
return str.replace(/,/g, '');
}

Just with JavaScript (without jQuery):
var money={"money1":"957.06","money2":"1,368,737.85"};
Object.keys(money).map(function(value, index) {
money[value] = money[value].replace(/,/g, '');
});
console.log(money);
// Object {money1: "957.06", money2: "1368737.85"}

Related

Extract values from href attribute string using JQuery

I would like to extract values from href attribute string using JQuery
$(this).attr("href")
will give me
?sortdir=ASC&sort=Vendor_Name
What i need is these values parsed into an array
myArray['sort']
myArray['sortdir']
Any ideas?
Thanks!
BTW , I saw somewhere else on SO the following similar idea to be used with a query string.
I could not tweak it for my needs just yet.
var urlParams = {};
(function () {
var match,
pl = /\+/g, // Regex for replacing addition symbol with a space
search = /([^&=]+)=?([^&]*)/g,
decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
query = window.location.search.substring(1);
while (match = search.exec(query))
urlParams[decode(match[1])] = decode(match[2]);
})();
Try the following:
var href = $(this).attr("href")
href = href.replace('?', "").split('&');
var myArr = {};
$.each(href, function(i, v){
var s = v.split('=');
myArr[s[0]] = s[1];
});
DEMO
Try this
function getURLParameter(name, string) {
return decodeURI(
(RegExp(name + '=' + '(.+?)(&|$)').exec(string)||[,null])[1]
);
}
var string = $(this).attr("href");
alert(getURLParameter("sort",string));
Demo here http://jsfiddle.net/jbHa6/ You can change the var string value and play around.
EDIT
Removed the second example, since that code is not that good and does not serve the purpose.
Perhaps is there a better solution but to be quick I should have do something like that
var url = $(this).attr("href");
url = url.replace("?sortdir=", "");
url = url.replace("sort=", "");
myArray['sort'] = url.split("&")[1]; // Or use a temporary tab for your split
myArray['sortdir'] = url.split("&")[0];
That solution depends if your url is still like ?sortdir=ASC&sort=Vendor_Name
You could use jQuery BBQ's deparam function from here:
http://benalman.com/code/projects/jquery-bbq/examples/deparam/

Any javascript string function?

Some outside code is giving me a string value like..
null,402,2912,2909,2910,2913,2911,2914,2915,2388,2389,2390,
now i have to save this value to the data base but putting 0 in place of null in javascript. Is there any javascript string releated function to do this conversion?
You can simply use the replace function over and over again until all instances are replaced, but make sure that all your string will ever contain is the character sequence null or a number (and obviously the delimiting comma):
var str = "null,402,2912,null"
var index = str.indexOf("null");
while(index != -1) {
str = str.replace("null", "0");
index = str.indexOf("null");
}
You need to run a for loop because the function String.replace(search, rplc) will replace only the first instance of search with rplc. So we use the indexOf method to check, in each iteration, if the required term exists or not. Another alternative (and in my opinion, a better alternative would be:
var str = "null,402,2912,null"
var parts = str.split(",");
var data = []
for(var i=0; i<parts.length; i++) {
data[data.length] = parts[i]=="null"?0:parseInt(parts[i]);
}
Basically, what we are doing is that since you will anyways be converting this to an array of numbers (I presume, and sort of hope), we first split it into individual elements and then inspect each element to see if it is null and make the conversion accordingly.
This should answer your needs:
var str = 'null,402,2912,2909,2910,2913,2911,2914,2915,2388,2389,2390';
str.split(",").map(function (n) { var num = Number(n); return isNaN(num) ? 0 : num; });
The simplest solution is:
var inputString = new String("null,402,2912,2909,2910,2913,2911,2914,2915,2388,2389,2390,");
var outputString = inputString.replace("null", "0");
What I understood from your question is:
You want to replace null with 0 in a string.
You may use
string = "null,402,2912,2909,2910,2913,2911,2914,2915,2388,2389,2390,"
string.replace(/null/g,0)
Hope it helps.

selecting second string point using js substring

i want to select a sting from the long para. it has number of dot('.')s. i want to trim the word from the second one, is it any way to do this?
example
var name = "one.two.three";
name.substring(0,name.indexOf('.'))
name.substring(0,name.lastIndexOf('.'))
from above trimming in case if i use indexOf it gives first word (one), if i use lastIndex of it gives the word (three), but i need to select the second one, to get value as 'second'
how can i trim this using indexOf method? or to select multicombination strings like one.three or one.two, or two.three?
thanks in advance!
use string.split.
e.g.
name.split(".")[1]
var name="one.two.three";
var result=name.split(".").slice(0,2).join(".");
Example:
"".split(".").slice(0,2).join(".") // return ""
"one".split(".").slice(0,2).join(".") // return "one"
"one.two".split(".").slice(0,2).join(".") // return "one.two"
"one.two.three".split(".").slice(0,2).join(".") // return "one.two"
"one.two.three.four.five".split(".").slice(0,2).join(".") // return "one.two"
Is that work for you ?
var name = "one.two.three";
var params = name.split('.');
console.log(params[1]);
use Split
var name = "one.two.three";
var output = name.split('.');
alert(output[1]);
example here

Quick Problem - Extracting numbers from a string

I need to extract a single variable number from a string. The string always looks like this:
javascript:change(5);
with the variable being 5.
How can I isolate it? Many thanks in advance.
Here is one way, assuming the number is always surrounded by parentheses:
var str = 'javascript:change(5);';
var lastBit = str.split('(')[1];
var num = lastBit.split(')')[0];
Use regular expressions:-
var test = "javascript:change(5);"
var number = new RegExp("\\d+", "g")
var match = test.match(number);
alert(match);
A simple RegExp can solve this one:
var inputString = 'javascript:change(5);';
var results = /javascript:change\((\d+)\)/.exec(inputString);
if (results)
{
alert(results[1]); // 5
}
Using the javascript:change part in the match as well ensures that if the string isn't in the proper format, you wont get a value from the matches.
var str = 'javascript:change(5);', result = str.match(/\((\d+)\)/);
if ( result ) {
alert( result[1] )
}

JavaScript indexOf to ignore Case

I am trying to find if an image has in its source name noPic which can be in upper or lower case.
var noPic = largeSrc.indexOf("nopic");
Should I write :
var noPic = largeSrc.toLowerCase().indexOf("nopic");
But this solution doesn't work...
You can use regex with a case-insensitive modifier - admittedly not necessarily as fast as indexOf.
var noPic = largeSrc.search(/nopic/i);
No, there is no case-insensitive way to call that function. Perhaps the reason your second example doesn't work is because you are missing a call to the text() function.
Try this:
var search = "nopic";
var noPic = largeSrc.text().toLowerCase().indexOf(search.toLowerCase());
Note that if the search string is from user input you'll need to escape the special regexp characters.
Here's what it would look like:
var search = getUserInput();
/* case-insensitive search takes around 2 times more than simple indexOf() */
var regex = RegExp(search.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), "i");
var noPic = testString.search(regex);
See the updated jsperf: http://jsperf.com/regex-vs-tolowercase-then-regex/4
footnote: regexp escaping from https://stackoverflow.com/a/3561711/1333402
Try with:
var lowerCaseLargeSrc = largeSrc.toLowerCase();
var noPic = lowerCaseLargeSrc.indexOf("nopic");
Your code will only work if largeSrc is already a string. You might be getting an input that's an html element instead. So, use jQuery to resolve any potential input element into the text that's inside it. Example:
var noPic = largeSrc.text().toLowerCase().indexOf("nopic");
How about using findIndex instead that way you can do all your toLowerCase() inside the callback. Worked great for me:
// Not Supported in IE 6-11
const arr = ['HELLO', 'WORLD'];
const str = 'world';
const index = arr.findIndex(element => {
return element.toLowerCase() === str.toLowerCase();
});
console.log(index); // 👉️ 1
if (index !== -1) {
// 👉️ string is in the array
}
Credit:
https://bobbyhadz.com/blog/javascript-make-array-indexof-case-insensitive

Categories

Resources