This question already has answers here:
What is the shortest function for reading a cookie by name in JavaScript?
(20 answers)
Closed 2 years ago.
I have this string
"G_ENABLED_IDPS=app; COOKIE_EINF=someCookie; _ga=someGA;
_hjid=someHJID; _gcl_au=someglcau; COOKIE_EINF_SESS=somecookie1; _gid=somegid; _hjIncludedInPageviewSample=2; _hjTLDTest=3; _hjAbsoluteSessionInProgress=0; _hjIncludedInSessionSample=1; _gat_UA-124355-12=5"
And i need some sort of function to split this string given an argument , for example given that my string is text
text.split(";") , will split it into an array separating it by ";"
But i need a function like this
returnText(text , property) that would work like
returnText(text, "_gcl_au") --> returns "someglcau"
You could actually use a regex replacement approach here, for a one-liner option:
function returnText(text, property) {
var term = text.replace(new RegExp("^.*\\b" + property + "=([^;]+)\\b.*$", "gm"), "$1");
return term;
}
var input = "G_ENABLED_IDPS=app; COOKIE_EINF=someCookie;_ga=someGA;_hjid=someHJID; _gcl_au=someglcau; COOKIE_EINF_SESS=somecookie1; _gid=somegid; _hjIncludedInPageviewSample=2; _hjTLDTest=3; _hjAbsoluteSessionInProgress=0; _hjIncludedInSessionSample=1; _gat_UA-124355-12=5";
console.log(returnText(input, "_gcl_au"));
you can use split, just as you tried:
function returnText(text , property){
entries = text.split('; ');
const newEntries = [];
entries.forEach(item => {
let vals = item.split('=');
newEntries[vals[0]] = vals[1]
});
return newEntries[property];
}
const text = "G_ENABLED_IDPS=app; COOKIE_EINF=someCookie; _ga=someGA;_hjid=someHJID; _gcl_au=someglcau; COOKIE_EINF_SESS=somecookie1; _gid=somegid; _hjIncludedInPageviewSample=2; _hjTLDTest=3; _hjAbsoluteSessionInProgress=0; _hjIncludedInSessionSample=1; _gat_UA-124355-12=5";
console.log(returnText(text,'_gcl_au'));
Related
This question already has answers here:
How to get the nth occurrence in a string?
(14 answers)
Closed 2 years ago.
For example, I have a string like following
var string = "test1;test2;test3;test4;test5";
I want the following substring from the above string, I don't know the startIndex, the only thing I can tell substring should start after the second semicolon to till the end.
var substring = "test3;test4;test5";
Now I want to have substring like following
var substring2 = "test4;test5"
How to achieve this in JavaScript
You mean this?
const string = "test1;test2;test3;test4;test5";
const arr = string.split(";")
console.log(arr.slice(2).join(";")); // from item #2
console.log(arr.slice(-2).join(";")) // last 2 items
If the string is very long, you may want to use one of these versions
How to get the nth occurrence in a string?
As a function
const string = "test1;test2;test3;test4;test5";
const restOfString = (string,pos) => {
const arr = string.split(";")
return arr.slice(pos).join(";"); // from item #pos
};
console.log(restOfString(string,2))
console.log(restOfString(string,3))
Try to use a combination of string split and join to achieve this.
var s = "test1;test2;test3;test4;test5";
var a = s.split(";")
console.log(a.slice(3).join(";"))
This question already has answers here:
Transform Javascript Array into delimited String
(7 answers)
Closed 4 years ago.
Im trying to convert at object array with jQuery or javascript to a comma separated string, and no matter what I try I canĀ“t get it right.
I have this from a select value.
ort = $('#ort').val();
ort=JSON.stringify(ort)
ort=["Varberg","Halmstad","Falkenberg"]
How can I convert it to a string looking like this?
ort=Varberg,Halmstad,Falkenberg
Any input appreciated, thanks.
You can use join
let arr = ["Varberg","Halmstad","Falkenberg"]
console.log(arr.join(','))
Use Array.prototype.join to to convert it into a comma separated string.
let str = ort=["Varberg","Halmstad","Falkenberg"].join(","); //"," not needed in join
console.log(str);
A simple toString also works in this case.
let str = ort=["Varberg","Halmstad","Falkenberg"].toString();
console.log(str);
Another way to achieve this is by using Array.prototype.reduce:
console.log(["Varberg", "Halmstad", "Falkenberg"].reduce((s, el, idx, arr) => {
s += el
if (idx < arr.length - 1) {
s += ','
}
return s;
}, ''));
This question already has answers here:
How to convert URL parameters to a JavaScript object? [duplicate]
(34 answers)
Closed 8 years ago.
var url = "journey?reference=123line=A&destination=China&operator=Belbo&departure=1043&vehicle=ARC"
How can I split the string above so that I get each parameter's value??
You could use the split function to extract the parameter pairs. First trim the stuff before and including the ?, then split the & and after that loop though that and split the =.
var url = "journey?reference=123line=A&destination=China&operator=Belbo&departure=1043&vehicle=ARC";
var queryparams = url.split('?')[1];
var params = queryparams.split('&');
var pair = null,
data = [];
params.forEach(function(d) {
pair = d.split('=');
data.push({key: pair[0], value: pair[1]});
});
See jsfiddle
Try this:
var myurl = "journey?reference=123&line=A&destination=China&operator=Belbo&departure=1043&vehicle=ARC";
var keyval = myurl.split('?')[1].split('&');
for(var x=0,y=keyval.length; x<y; x+=1)
console.log(keyval[x], keyval[x].split('=')[0], keyval[x].split('=')[1]);
to split line in JS u should use:
var location = location.href.split('&');
This question already has an answer here:
Get part of the string using regexp [closed]
(1 answer)
Closed 9 years ago.
Here's an example http://jsbin.com/USONirAn/1
var string = "some text username#Jake# some text username#John# some text some text username#Johny# userphoto#1.jpg#";
var type = "username";
var regexp = new RegExp(type + "#(.*?)#");
var matches = string.match(regexp);
Current regexp returns into matches an array with 3 items - [username#Jake#, username#John#, username#Johny#].
How do I make it return only a strings that I used to search for - (.*?)? In this example is should be an array [Jake, John, Johny]. Is it possible to get this only by changing a regexp function?
Update:
I've also tried to use exec function, but it returns both [username#Jake#, Jake] http://jsbin.com/USONirAn/6
Search-and-don't-replace
var matches = []
string.replace(regexp, function () {
matches.push(arguments[1]);
});
http://jsbin.com/USONirAn/4
This question already has answers here:
JavaScript reverse the order of letters for each word in a string
(5 answers)
How do you reverse a string in-place in JavaScript?
(57 answers)
Closed 9 years ago.
Was wondering if you can reverse a string and still maintain the order.
Below is a function that returns "dlroW olleH" and I want to return "olleH dlroW"
var myFunction = function() {
var userdata = document.getElementById('data').value,
uRev = userdata.split("").reverse().join("");
document.getElementById('results').innerHTML = uRev;
};
Thanks!
Reverse the words and then the characters:
var myFunction = function() {
var userdata = document.getElementById('data').value,
uRev = userdata.split(" ").reverse().join(" ").split("").reverse().join("");
document.getElementById('results').innerHTML = uRev;
};
Example JSFiddle
function reverseString(s){
return s.split("").reverse().join("");
}
function reverseEachWord(s) {
return s.split(" ").map(reverseString).join(" ");
alert(userdata.split(" ").reverse().join(" ").split("").reverse().join(""));
first split your string in an array of words using split(" "), then split each array segment using the method above.
Try this,
var myFunction = function() {
var resArr=[];
var userdata = document.getElementById('data').value,
uRev = userdata.split("");
for (var i=0;i<uRev.length;i++){
resArr.push(uRev[i].reverse());
}
document.getElementById('results').innerHTML = resArr.join('');
};
var test = 'Hello World';
alert(
test.replace(
/\w+/g ,
function(a){return a.split('').reverse().join('');}
)
);