Javascript string to array(if string is without any space) - javascript

I have a string for e.g:
var str = 'abcdef';
i want to get it in an array format e.g:
var a;
a[0]=a;
a[1]=b; and so on..
i am aware of split method but in this case of string without any space how can i split as individual character??

Use: str.split(''). That will create an array with characters of str as elements.

You can access it like this ,
var str='abcdef';
alert(str[0]);
or
var str='abcdef';
alert(str.charAt(0));
refer following link to chose which is the best way.
http://blog.vjeux.com/2009/javascript/dangerous-bracket-notation-for-strings.html

var s = "abcdef";
var a;
for (var i = 0; i < s.length; i++) {
a.push(s.charAt(i));
}
or
var s = "abcdef";
var a;
var a= s.split('');

Try using this code:-
var array = str.split('');
Look at the following page to know more about splits.
Javascript split

var str="abcdef";
var a=new Array;
for (var x=0; x<str.length; x++) {
a[x] = str.charAt(x);
}
console.log(a);

Related

How to cut a string in this case in JavaScript?

Example:
let somestr = '11>22>33>44';
let someSpecificWord = '22';
I want to get a result like this
'11>22'
How to cut or use method for this?
You may use String#substring with String#lastIndexOf:
let somestr = '11>22>33>44';
let someSpecificWord = '22';
console.log(somestr.substring(0, somestr.lastIndexOf(someSpecificWord) + someSpecificWord.length));
In case u want all of the numbers included in result.
var str = '11>22>33>44';
var splitstr = str.split('>');
var strarray =[];
for(var i=0; i<splitstr.length-1;i++){
strarray[i] = splitstr[i]+'>'+splitstr[i+1];
$("span").append(strarray[i]+"<br />");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="span"></span>
You can also split() the string to array and then find the indexOf() the work, then join() using > to get the final result. For better code management, create a reusable function.
function cutWord(str, word){
var splitStr = str.split('>');
return splitStr.slice(0,splitStr.lastIndexOf(someSpecificWord)+1).join('>');
}
var somestr = '11>22>33>44';
var someSpecificWord = '22';
console.log(cutWord(somestr, someSpecificWord));
someSpecificWord = '33';
console.log(cutWord(somestr, someSpecificWord));
someSpecificWord = '11';
console.log(cutWord(somestr, someSpecificWord));

How to translate an input using a function in JavaScript

So the goal of this task is translate english input values into french and vice versa. The problem here is that I don't know how to split the whole input by spaces to get all the words one by one and translate them one by one. Thank you :)
function translateInput(){
for(i = 0; i < ('input').length; i++){
('input').eq(i).val(('value').eq(i).text());
}
}
var translateText = function() {
var translationType = document.getElementById('translation').value;
if (translationType === 'englishToFrench') {
console.log('translation used: English to French');
return 'code1';
}else if(translationType === 'frenchToEnglish'){
console.log('translation used: French to English');
return 'code2';
}else{
return "No valid translation selected.";
}
};
You can use the split function to split the string at its spaces into an array.
var str = YOUR_STRING;
var array = str.split(" ");
http://www.w3schools.com/jsref/jsref_split.asp
Then you can loop through the array and translate word by word.
var arrayLength = array.length;
for (var i = 0; i < arrayLength; i++) {
alert(array[i]);
//Translate string
}
Or you can use a Regular Expression, by the way you can practice in a Regex Playground.
var myString = "Hello, my name is JavaScript";
var tokens = a.match(/\w+'?\w*/g); //Assuming you can take words like {"Bonsanto's", "Asus'"}
tokens.forEach(function(word){
console.log(word);
});

Javascript pull data from string?

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.

Transform a string into array using javascript

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.

How to reference a javascript hash using a integer value when the key is a string?

My javascript hash on my web page looks like:
{"7":{"prop1":234, ....}"101":{"prop1":121,....}
I'm trying to reference it like this:
var a = 7;
my_hash[a].prop1
But it doesn't seem to find the hash object at the key 'a', since a is an integer and my keys are strings.
How can convert it to a string?
I tried:
my_hash[" + a + "].prop1
But that didn't work either.
Just create a string:
var a = "7";
If you have a number already, and want to make it a string, coerce it to a string this way:
var n = 7;
var a = n + "";
So, these all will work:
my_hash["7"].prop1;
var a = "7";
my_hash[a].prop1;
var n = 7;
var a = n + "";
my_hash[a].prop1;
Edit: Some examples converting it to a string inline:
my_hash[7 + ""].prop1;
var n = 7;
my_hash[n + ""].prop1;
Why not this:
var a = "7";
my_hash[a].prop1
or
my_hash["7"].prop1
Also, I'm assuming this was just a copy/paste into SO issue, but there's a missing comma in this:
{"7":{"prop1":234, ....}"101":{"prop1":121,....}
should be:
{"7":{"prop1":234, ....}, "101":{"prop1":121,....}
var x = {"7":{"prop1":234},"101":{"prop1":121}};
var a = 7;
console.log(x[a+""].prop1);
http://jsfiddle.net/userdude/ZGWHU/
You can coerce the number into a string like gilly3 suggests. But you can also just call .toString on the number itself. For example:
(1).toString() === "1" // evaluates to true.
This also works for variables so you could do this:
for (var i=0; i<10; i++) {
property = myObject[i.toString()]["property"];
// do something with property
}

Categories