I have an object in javascript -:
var array = {"1":"John","2":"Caprio","3":"David","4":"Edward"}
I want to do this -:
var message = 'Wats up David#1. Are you with David#5 or Caprio#89';
$.each(array, function(key, value){
var matchMe=value+'#'+anywholenumber;
if(message.match(matcheMe))
{
var ge = new RegExp(matchMe, 'g');
message = message.replace(ge,'['+matchMe+']');
} });
How do i do it? Thanks a lot for help
The code you have would replace every number with the first element (john) if it were working.
I think you want this:
var arr = array("John","Caprio","David","Edward","Suzy");
var message = 'Wats up David#1. Are you with David#5 or Caprio#2';
for (i=0; i < arr.length; i++) {
var re = new RegExp(i, 'g');
message = message.replace(re, arr[i]);
}
Related
Unable to split same string for two times.What i am doing wrong?
// my original string
var str = "Left,Right-broken at left side";
var ary = "Left,Right-broken at left side";
//getting text after - (working fine)
var res = str.split("-").pop();
$('#disc_comm_tlside_ed').empty();
$('#disc_comm_tlside_ed').val(res);
// with this i can get text before -once again i need to splt by comma only
var myarrays= str.substr(0, str.indexOf('-'));
//even this also returning original string
var splt = ary.split(',');
// alert(splt) when i alert this getting full string
for(var i = 0; i < splt.length; i++)
{
//alert(myarray[i]);
$(this).find("option[value ='"+myarray[i]+"']").attr("selected",true);
$('.batch_ed').multiselect('rebuild');
}
Finally returning original string!!
Need to get text before-and split text separated by ,
need to get left and right only as array
Edit: adding the code snippet posted in the comment.
var elements = "";
var batchnoe= "";
$.each(data.response.frc_disloc, function (a,b){
batchnoe = '.batch_ed';
$(batchnoe).each(function(i, obj) {
var batch_splt = b.frac_side;
var myarray = batch_splt.split(',');
for(var i = 0; i < myarray.length; i++) {
$(this).find("option[value ='"+myarray[i]+"']").attr("selected",true); $('.batch_ed').multiselect('rebuild');
}
});
});
please check console logs for the output.
// my original string
var str = "Left,Right-broken at left side";
var ary = "Left,Right-broken at left side";
//getting text after - (working fine)
var res = str.split("-").pop();
$('#disc_comm_tlside_ed').empty();
$('#disc_comm_tlside_ed').val(res);
// with this i can get text before -once again i need to splt by comma only
var myarrays= str.substr(0, str.indexOf('-'));
//even this also returning original string
var splt = myarrays.split(',');
console.log(splt);
// alert(splt) when i alert this getting full string
for(var i = 0; i < splt.length; i++)
{
console.log(splt[i]);
$(this).find("option[value ='"+splt[i]+"']").attr("selected",true);
//$('.batch_ed').multiselect('rebuild');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="disc_comm_tlside_ed"></div>
I have just one question maybe stupid (like every day)
var word = []; (an array with 100 words for example)
var tab = []; // resultat
var root = "test";
var debut = "Anti";
var reg1=new RegExp("^"+debut + "+." + root,"g")
for(var i = 0;i<word.length; i++){
// a word begin with Anti and contain test pls
if (word[i].match(reg1)){´
tab.push(word[i])
}
}
console.log(tab.join(', ');
but it is dont work, i dont know how to use variable with regexpr, thanks, sorry for my english
var r = new RegExp('anti.*esis', 'ig')
document.write('antithesis'.match(r), '<br/>') // ["antithesis"]
document.write('antihero'.match(r), '<br/>') // null
Here is the code, but is used the test() instead of match()
var word=["yea","antiboyahtest","antigssjshbztest"];
var debut="anti";
var root="test";
var reg=new RegExp("^"+debut+".*"+root,"g");
var tabs=[];
for(i in word){
if(reg.test(word[i])){
tabs.push(word[i]);
}
}
alert(tabs);
The solution using RegExp.test and Array.filter functions:
var word = ['Antitest', 'Antidot', 'Anti-next-test', 'testAnti'],
root = "test", debut = "Anti",
reg1 = new RegExp("^"+debut + ".*?" + root, "g");
var result = word.filter(function (w) {
return reg1.test(w);
});
console.log(result); // ["Antitest", "Anti-next-test"]
Also, there's an additional approach using Array.indexOf function without any regex which will give the same result:
...
var result = word.filter(function (w) {
return w.indexOf(debut) === 0 && w.indexOf(root) !== -1;
});
how can i make this work:
var storedValues = $('<table class="table_groessentabelle_custom"></table>');
// contains excel paste content from Libreoffice
$('textarea[name=excel_data]').bind("paste", function(e){
var pastedData = e.originalEvent.clipboardData.getData('text/html');
storedValues.append(pastedData);
});
//localisation - tables (just a subset)
var de = ["Größe","Höhe","Weite","Damen","Herren","Kinder",];
var fr = ["Pointure","Hauteur","Largeur","Femme","Homme","Enfants"];
var de_storedvalues = JSON.parse(JSON.stringify( storedValues.html() ));
var fr_storedvalues = JSON.parse(JSON.stringify( storedValues.html() ));
for (var i = 0; i < de.length; i++) {
// doesnt work, no fields are translated
fr_storedvalues = fr_storedvalues.replace(/de[i]/gi,fr[i]);
}
it works without the /gi flag but only transates the first entry of a given variable. if there is more than one entry, the rest stays in german.
Thanks in advance,
Michael
var find = de[i];
var regex = new RegExp(find, "g");
fr_storedvalues = fr_storedvalues.replace(regex,fr[i]);
I have a long URL that contains some data that I need to pull. I am able to get the end of the URL by doing this:
var data = window.location.hash;
When I do alert(data); I receive a long string like this:
#access_token=0u2389ruq892hqjru3h289r3u892ru3892r32235423&token_type=Bearer&expires_in=3600
note in the example the access token is not valid, just random numbers I input for example purpose
Now that I have that long string stored in a variable, how can I parse out just the access token value, so everything in between the first '=' and '&. So this is what I need out of the string:
0u2389ruq892hqjru3h289r3u892ru3892r32235423
I was reading up on php explode, and others java script specific stuff like strip but couldn't get them to function as needed. Thanks guys.
DEMO (look in your debug console)
You will want to split the string by the token '&' first to get your key/value pairs:
var kvpairs = document.location.hash.substring(1).split('&');
Then, you will want to split each kvpair into a key and a value:
for (var i = 0; i < kvpairs.length; i++) {
var kvpair = kvpairs[i].split('=');
var k = kvpair[0];
var v = kvpair[1];
if (k != 'access_token')
continue;
console.log(v); //Here's your access token.
}
Here is a version wrapped into a function that you can use easily:
function getParam(hash, key) {
var kvpairs = hash.substring(1).split('&');
for (var i = 0; i < kvpairs.length; i++) {
var kvpair = kvpairs[i].split('=');
var k = kvpair[0];
var v = kvpair[1];
if (k != key)
continue;
return v;
}
return null;
}
Usage:
getParam(document.location.hash, 'access_token');
data.split("&")[0].split("=")[1]
var str = "#access_token=0u2389ruq892hqjru3h289r3u892ru3892r32235423&token_type=Bearer&expires_in=3600";
var requiredValue = str.split('&')[0].split('=')[1];
I'd use regex in case value=key pair changes position
var data = "#token_type=Bearer&access_token=0u2389ruq892hqjru3h289r3u892ru3892r32235423&expires_in=3600";
RegExp("access_token=([A-Za-z0-9]*)&").exec(data)[1];
output
"0u2389ruq892hqjru3h289r3u892ru3892r32235423"
Looks like I'm a bit late on this. Here's my attempt at a version that parses URL parameters into a map and gets any param by name.
var str = "#access_token=0u2389ruq892hqjru3h289r3u892ru3892r32235423&token_type=Bearer&expires_in=3600";
function urlToMap(url){
var startIndex = Math.max(url.lastIndexOf("#"), url.lastIndexOf("?"));
url = url.substr(startIndex+1);
var result = {};
url.split("&").forEach(function(pair){
var x = pair.split("=");
result[x[0]]=x[1];
});
return result;
}
function getParam(url, name){
return urlToMap(url)[name];
}
console.log(getParam(str, "access_token"));
To answer to your question directly (what's between this and that), you would need to use indexOf and substring functions.
Here's a little piece of code for you.
function whatsBetween (_strToSearch, _leftText, _rightText) {
var leftPos = _strToSearch.indexOf(_leftText) + _leftText.length;
var rightPos = _strToSearch.indexOf(_rightText, leftPos);
if (leftPos >= 0 && leftPos < rightPos)
return _strToSearch.substring(leftPos, rightPos);
return "";
}
Usage:
alert(whatsBetween, data,"=","#");
That said, I'd rather go with a function like crush's...
try this
var data = window.location.hash;
var d1 = Array();
d1 = data.split("&")
var myFilteredData = Array();
for( var i=0;i<d1.length;i++ )
{
var d2 = d1[i].split("=");
myFilteredData.push(d2[1]); //Taking String after '='
}
I hope it helps you.
I have a string like this:
string = "locations[0][street]=street&locations[0][street_no]=
34&locations[1][street]=AnotherStreet&locations[1][street_no]=43";
What must I do with this string so i can play with locations[][] as I wish?
You could write a parser:
var myStr = "locations[0][street]=street&locations[0][street_no]=34&locations[1][street]=AnotherStreet&locations[1][street_no]=43";
function parseArray(str) {
var arr = new Array();
var tmp = myStr.split('&');
var lastIdx;
for (var i = 0; i < tmp.length; i++) {
var parts = tmp[i].split('=');
var m = parts[0].match(/\[[\w]+\]/g);
var idx = m[0].substring(1, m[0].length - 1);
var key = m[1].substring(1, m[1].length - 1);
if (lastIdx != idx) {
lastIdx = idx;
arr.push({});
}
arr[idx * 1][key] = parts[1];
}
return arr;
}
var myArr = parseArray(myStr);
As Shadow wizard said, using split and eval seems to be the solution.
You need to initialize locations first, if you want to avoid an error.
stringArray=string.split("&");
for (var i=0;i<stringArray.length;i++){
eval(stringArray[i]);
}
However, you might need to pay attention to what street and street_no are.
As is, it will produce an error because street is not defined.
Edit: and you'll need to fully initialize locations with as many item as you'll have to avoid an error.