How do i split in java script? - javascript

I have a two dimensional array which consists of versions like,
say,
var version = [[B2.0.2.1],[B3.0.2.1], and many more];
How do I split B from these versions because I am only interested in the version that is 2.0.2.1 and so on?

The slice method will be useful in solving your problem.
Here is an example:
var str = "B2.0.2.1";
var res = str.slice(1); // Will result in second character until the end.
// res = "2.0.2.1"
If you use it with a single parameter str.slice(1); you will effectively cut off the first character leaving you with just the version number.. This is assuming that only one letter ever prefixes the versions numbers.

Use array.map to manipulate each element in array
var version = [['B2.0.2.1'],['B3.0.2.1']];
version = version.map(function(ver){
return [ver[0].slice(1)];
});

The simplest way, without loops is using JSON methods
var stripped = JSON.parse(JSON.stringify(version).replace(/B/g, ''));
console.log(stripped);
In this case, I don't even care that your original code is invalid javascript, nor what you'd need to do to fix it, this will get rid of all B's regardless

Related

Ellegant find regEx in array

I want to launch one script if one off several browsers are detected. I made an array with regulars and I want to check if one of them exists in navigator.userAgent string. I want to do it with underscore without FOR EACH.
var browsers = [/chrome/, /opera/];
/* something like: */
if (!_.contains(browsers, navigator.userAgent.toLowerCase()) return;
Using _.some():
if (!_.some(browsers, function(item){
return navigator.userAgent.toLowerCase().test(item);
}) return;
However, I'd recommend using #dystroy's single-regex solution. It's faster, shorter code.
You could do that like this:
var arr = ["chrome", "opera"]; // Strings, not regexes.
var regexp = new RegExp(arr.join('|'), 'i');
if (!regexp.test(navigator.userAgent)) return;
Or, as a one-liner:
if (!RegExp(["chrome", "opera"].join('|'), 'i').test(navigator.userAgent)) return;
A better solution would be to have only one regex, so that you don't have to iterate. And using the i flag lets you avoid the toLowerCase :
if (!/chrome|opera/i.test(navigator.userAgent)) return;

Replace Word Within Word - Javascript

I need to get a id from a html element and replace a part of the word. For example:
HTML
<input type="checkbox" id="facebookCheckbox"></div>
JavaScript
var x = document.getElementById("facebookCheckbox");
var name = x.id;
name.replace("Checkbox","");
This obviously does not work because the replacing word has to be standalone for it to be replaced. Is there a different way of doing this?
I'm looking for purely javascript no jQuery
Thank you!
name.replace("Checkbox","");
This obviously does not work because the replacing word has to be standalone for it to be replaced.
No, it does work and there's no need to be "standalone" - any part of the string can be matched. Only you did nothing with the result of the operation:
console.log(name.replace("Checkbox",""));
// or
name = name.replace("Checkbox","");
// or assign back to x.id maybe?
You are creating a copy of string when replacing, so you must assign the result of .replace() back to x.id.
var x = document.getElementById("facebookCheckbox");
x.id = x.id.replace("Checkbox","");
this is not going to work in this way. However you can have a marker kind of character by which you can break the name into array and implement the logic. For example:
var x = document.getElementById("facebook_Checkbox");
//Note I have added underscore in the Id
var name = x.id;
var arr=name.split("_");
//Now you have Checkbox and Facebook as string objects (part of array) and you can use them
name=arr[0]
I hope it will solve the purpose.

javascript regex - remove a querystring variable if present

I need to rewrite a querysting using javascript.
First I check to see if the variable is present, if it is I want to replace it with a new search term. If it is not present then I just add the new variable
I'm able to get it to work with simple terms like hat, ufc hat
whitespaces are %20, so ufc hat is really ufc%20hat
I run into problem with terms like make-up, hat -baseball, coffee & tea, etc..
What is the proper regex for this?
Below is my code, which doesn't work.
var url = String(document.location).split('?');
querystring = url[1];
if(querystring.match(/gbn_keywords=/)!=null)
querystring=querystring.replace(/gbn_keywords=[a-zA-Z0-9%20.]+/,"gbn_keywords="+term);
else
querystring=querystring+"&gbn_keywords="+term;
No Regex needed. To get the query arguments, take everything after ?. Then, split the string by & to return each argument. Split again by = to get the arg name (right of =) and the value (left of =). Iterate through each argument, a rebuild the URL with each argument, excluding the one you don't want. You shouldn't run into problems here because ?, &, and - must be escaped if they are to be used in arguments. You also said you want to add the argument if it doesn't exist, so just set a variable to true, while you are iterating through each argument, if you find the argument. If you didn't append it to the end of the query string that you rebuilt.
location objects already have perfectly good properties like pathname, hostname etc. that give you the separate parts of a URL. Use the .search property instead of trying to hack the URL as a string (? may not only appear in that one place).
It's then a case of splitting on the & character (and maybe ; too if you want to be nice, as per HTML4 B2.2) and checking each parameter against the one you're looking for. For the general case this requires proper URL-decoding, as g%62n_keywords=... is a valid way of spelling the same parameter. On the way out naturally you will need to encode again, to stop & going on to the next parameter (as well as to include other invalid characters).
Here's a couple of utility functions you can use to cope with query string manipulation more easily. They convert between the ?... string as seen in location.search or link.search and a lookup Object mapping parameter names to arrays of values (since form-url-encoded queries can have multiple instances of the same parameter).
function queryToLookup(query) {
var lookup= {};
var params= query.slice(1).split(/[&;]/);
for (var i= 0; i<params.length; i++) {
var ix= params[i].indexOf('=');
if (ix!==-1) {
var name= decodeURIComponent(params[i].slice(0, ix));
var value= decodeURIComponent(params[i].slice(ix+1));
if (!(name in lookup))
lookup[name]= [];
lookup[name].push(value);
}
}
return lookup;
}
function lookupToQuery(lookup) {
var params= [];
for (var name in lookup)
for (var i= 0; i<lookup[name].length; i++)
params.push(encodeURIComponent(name)+'='+encodeURIComponent(lookup[name][i]));
return params.length===0? '' : '?'+params.join('&');
}
This makes the usage as simple as:
var lookup= queryToLookup(location.search);
lookup['gbn_keywords']= ['coffee & tea'];
var query= lookupToQuery(lookup);
& character is used to seperate key and value pairs in the querystring. So that you can match all the characters except for & by re-writing your code as follows:
querystring=querystring.replace(/gbn_keywords=[^&]+/,"gbn_keywords="+term);
[^&]+ matches one or more characters up to & or end of string. But if there may situations where the querystring data may look like ...?gbn_keywords= (no value) then a slight modification is needed to the above line:
querystring=querystring.replace(/gbn_keywords=[^&]*/,"gbn_keywords="+term);
Just change + to * so that the regex will match 0 or more characters. I think this is better.
Why don't you run a split on url[1] and than replace the value of the gbn_keywords in that new array?
And if you use a JavaScript Framework, there might be a handy function that does all that. In Prototype there is the function toQueryParams().

JavaScript: dynamic regex for my own parser

I am trying a new direction in Language Kits (or whatever you want to call those multi language text files with placeholders). Basically, I have text like this: Hello, my name is %0. Welcome to %1!. This would be my pText.
My pValues is an array whose values represent %0 and %1.
The following function should find %0 and replace it with pValues[0] and so on.
function _parseDialogMessage(pText, pValues) {
var result = pText;
for (var i=0; i<pValues.length; ++i) {
var regex = new RegExp('\%'+i, 'gi');
pText = pText.replace(regex, pValues[i]);
}
return result;
}
It all works except for the fact that it does not replace the placeholders %0 and %1. All Variables have the expected values but .replace doesn't seem to find my placeholders.
Any help?
Edit 1
Shame on me... -.-
You don't need "dynamic regex", since replace can take a function as argument:
function _parseDialogMessage(pText, pValues) {
return pText.replace(/%(\d+)/g, function (s, i) { return pValues[i]; });
}
(and you should return pText.)
You are returning the result variable which hold the initial values of the ptext parameter..
return the pText variable..
UUhm, you return result and not the replace pText
While you can't use any of their code unless you want to GPL your library, the manual for gnu's gettext covers the rationale behind a number of topics related to internationalization.
http://www.gnu.org/software/gettext/manual/gettext.html
edit : I know you're just looking for a magic regex, but it won't be enough.
easy example :
I have %n computers.
I have 1 computers.
Did you know arabic has a special tense for 2 things, and chinese no tense for the number of things referred to?

Parsing every element of an array as an integer

I have a string which I need to split into an array and then perform mathematical functions on each element of the array.
Currently I am doing something like this. (Actually, I am doing nothing like this, but this is a very simple example to explain my question!
var stringBits = theString.split('/');
var result = parseInt(stringBits[0]) + parseInt(stringBits[3]) / parseInt(stringBits[1]);
What I would like to know is if there is a way I can convert every element of an array into a certain type that would stop me from having to explicitly parse it each time.
An easier method is to map to the Number object
result= stringBits.map(Number);
javascript 1.6. has map() ( https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Objects/Array/Map ), so you can do something like
intArray = someArray.map(function(e) { return parseInt(e) })
You can just loop through it:
for(var i = 0; i < stringBits.length; i++) {
stringBits[i] = parseInt(stringBits[i]);
}
["1","2"].map(Number)
result: [1,2]
If you add a plus (+) sign in front of your strings they should be converted to numeric.
For example, this will print 3:
var x = "1";
var y = "2";
alert((+x) + (+y));
But I am not sure if this is portable to all browsers.
Your code will become:
var stringBits = theString.split('/');
var result = (+stringBits[0]) + (+stringBits[3]) / (+stringBits[1]);
But this is just a hack, so use with care.
I think the parseInt states better what you are trying to do, but you should delegate this responsibility to another method that returns the final data that you need to process. Convert and then process, don’t convert while processing. Your code will be easier to read.

Categories

Resources