Break the string in positions in javascript - javascript

I need to split the string according to the positions not a string array just single string. I wrote following code and works fine. But is there any way to do it handy manner ?
function breakString(str, postion) {
var newStr;
var arr = [], res = [];
arr = str.split("");
for(var i = 0; i < postion; i++){
res[i] = arr[i]
newStr = res.join("");
}
return newStr;
}
console.log(breakString("rasika", 3));

There are the 2 ways that I can suggest you to use for this task.
✓ Using slice() method.
✓ Using split(), slice() & join() methods in conjunction.
http://rextester.com/CNVUP86671
var name = "rasika";
console.log(name.slice(0,3)); // ras
console.log(name.split("").slice(0, 3).join("")); // ras

easy manner
var arr = "Rasika";
console.log(arr.substring(0,3));

Related

Pushing first character at last and returning the string

I was trying to find out a way where I can push the first character to the last and return the rest of the string.
suppose like reverse("aeiou") should be able to return
eioua
iouae
ouaei
uaeio
function strR(str){
var a = str.split('');
var tmp =[];
a.map (item => {tmp.unshift(item)
console.log(tmp);
})
}
strR("aeiou")
aeiou
I tried a lot seems not working . If anyone can help me would be really appreciated.
let bla = "aeiou";
for (let i = 0; i < bla.length; i++) {
bla = bla.slice(1) + bla[0];
console.log(bla);
}
Try this! Alert data can print out wherever
function myFunction() {
var str = "aeiou";
var count = str.length;
for (i = 0; i < str.length; i++) {
var res = str.substring(0, 1);
var result = str.slice(1);
var data = result + res;
str = data;
alert(data);
}
}
<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">Try it</button>
</body>
</html>
Just use substr to remove the first character and charAt to add it to the end.
var string = 'aeiou'
i=0
while (i < 10) {
string = string.substr(1) + string.charAt(0);
console.log(string);
i++;
}
Maybe you are looking for this.
let input = "aeiou";
let chunk = input.split("");
let output = [];
for(let i=0; i<chunk.length;i++){
let last = chunk.shift();
chunk.push(last);
output.push(chunk.toString().replace(/,/g, ''));
}
console.log("Output", output.toString());
Here is one liner using Array.from and slice methods.
const str = "aeiou";
const str_arr = Array.from(
new Array(str.length),
(_, i) => `${str.slice(i, str.length)}${str.slice(0, i)}`
);
console.log(str_arr);
there is a short and easier way for do that:
function FirstToEnd (str){
return str.substr(1) + str[0]
}
and for result all possible data:
function FirstToEndAllPossible(str) {
let result = [];
for (let i = 0; i < str.length; i++) {
str = str.substr(1) + str[0];
result.push(str);
}
return result;
}
good luck :)
Try This:
var string = 'aeiou'
i=0
while (i < string.length-1) {
string = string.substr(1) + string.charAt(0);
console.log(string);
i++;
}
You can use like this. Calling Recursion - Works for all the Strings.
var InputStr = 'aeiou';
var i = 0;
var word = [];
function callqueue(InputStr, i)
{
StringLength = InputStr.length;
i = i+1;
if (i <= StringLength)
{
firstChar = InputStr.slice(0, 1);
remainStr = InputStr.substr(1);
word.push(remainStr+firstChar);
callqueue(remainStr+firstChar, i);
}
return word;
}
output = callqueue(InputStr, i);
console.log(output);
Try below code
function strR(str){
for (let i = 0; i < str.length-1; i++) {
str = str.substr(1)+str.charAt(0);
console.log(str);
}
strR('aeiou');
Your question is not quite clear. Hope the below solution works for you.
function strR(str){
var a = str.split('');
a[a.length] = a.shift();
return a.join('');
}
strR("aeiou")
/* or */
String.prototype.firstToLast = function() {
var a = this.split('');
a[a.length] = a.shift();
return a.join('');
}
"aeiou".firstToLast();
I find using an array for this kind of string manipulation a bit more readable.
In the function below, we start with splitting the string into an array.
The second step will be using the native .shit method which returns the first item in an array (in our case, the first letter) while modifying the Lastly, as we have the first character and the rest of the string we build them into a new array where we spread (...) the modified array and adding the first character at the end. The join('') method returns a string out of the new array.
function firstToLast (str) {
const split = str.split('');
const first = split.shift();
return [...split, first].join('');
}
Hopefully it's clear and helps with what you were trying to achieve
My go-to would be to use JavaScripts built-in array methods. You can break a string into an array of single characters using split with no parameters, and put it back together using join with an empty string as a parameter.
let word = 'sydney'
function rotate (anyword) {
let wordarray= anyword.split()
let chartomove = wordarray.splice(0, 1)[0]
wordarray.push(chartomove)
return wordarray.join('')
}
rotate(word) // returns 'ydneys'

What's the best way to convert cookie string to an object [duplicate]

I have a string similiar to document.cookie:
var str = 'foo=bar, baz=quux';
Converting it into an array is very easy:
str = str.split(', ');
for (var i = 0; i < str.length; i++) {
str[i].split('=');
}
It produces something like this:
[['foo', 'bar'], ['baz', 'quux']]
Converting to an object (which would be more appropriate in this case) is harder.
str = JSON.parse('{' + str.replace('=', ':') + '}');
This produces an object like this, which is invalid:
{foo: bar, baz: quux}
I want an object like this:
{'foo': 'bar', 'baz': 'quux'}
Note: I've used single quotes in my examples, but when posting your code, if you're using JSON.parse(), keep in your mind that it requires double quotes instead of single.
Update
Thanks for everybody. Here's the function I'll use (for future reference):
function str_obj(str) {
str = str.split(', ');
var result = {};
for (var i = 0; i < str.length; i++) {
var cur = str[i].split('=');
result[cur[0]] = cur[1];
}
return result;
}
The shortest way
document.cookie.split('; ').reduce((prev, current) => {
const [name, ...value] = current.split('=');
prev[name] = value.join('=');
return prev;
}, {});
Why exactly do you need JSON.parse in here? Modifying your arrays example
let str = "foo=bar; baz=quux";
str = str.split('; ');
const result = {};
for (let i in str) {
const cur = str[i].split('=');
result[cur[0]] = cur[1];
}
console.log(result);
note : The document.cookie (question headline) is semicolon separated and not comma separated (question) ...
An alternative using reduce :
var str = 'foo=bar; baz=quux';
var obj = str.split(/[;] */).reduce(function(result, pairStr) {
var arr = pairStr.split('=');
if (arr.length === 2) { result[arr[0]] = arr[1]; }
return result;
}, {});
A way to parse cookies using native methods like URLSearchParams and Object.fromEntries, avoiding loops and temporary variables.
Parsing document.cookie:
Object.fromEntries(new URLSearchParams(document.cookie.replace(/; /g, "&")))
For the scope of the question (cookies are separated by , and stored in variable str)
Object.fromEntries(new URLSearchParams(str.replace(/, /g, "&")))
Given an array a containing your intermediate form:
[['foo', 'bar'], ['baz', 'quux']]
then simply:
var obj = {};
for (var i = 0; i < a.length; ++i) {
var tmp = a[i];
obj[tmp[0]] = tmp[1];
}
To convert it to an object, just do that from the beginning:
var obj = {};
str = str.split(', ');
for (var i = 0; i < str.length; i++) {
var tmp = str[i].split('=');
obj[tmp[0]] = tmp[1];
}
Then, if you want JSON out of it:
var jsonString = JSON.stringify(obj);
parse cookies (IE9+):
document.cookie.split('; ').reduce((result, v) => {
const k = v.split('=');
result[k[0]] = k[1];
return result;
}, {})
I'm a fan of John Resig's "Search and don't replace" method for this sort of thing:
var str = 'foo=bar, baz=quux',
arr = [],
res = '{';
str.replace(/([^\s,=]+)=([^,]+)(?=,|$)/g, function ($0, key, value) {
arr.push('"' + key + '":"' + value + '"');
});
res += arr.join(",") + "}";
alert(res);
Working example: http://jsfiddle.net/cm6MT/.
Makes things a lot simpler without the need for JSON support. Of course, it's just as easy to use the same regular expression with exec() or match().
Whoops, I thought you wanted to convert to a JSON string, not an object. In that case, you only need to modify the code slightly:
var str = 'foo=bar, baz=quux',
res = {};
str.replace(/([^\s,=]+)=([^,]+)(?=,|$)/g, function ($0, key, value) {
res[key] = value;
});
console.log(res.foo);
//-> "bar"
Working example 2: http://jsfiddle.net/cm6MT/1/
Most of the above solutions fail with the __gads cookie that Google sets because it uses a '=' character in the cookie value.
The solution is to use a regular expression instead of calling split('='):
document.cookie.split(';').reduce((prev, current) => {
const [name, value] = current.split(/\s?(.*?)=(.*)/).splice(1, 2);
prev[name] = value;
return prev;
}, {});
That's pretty crappy data, as long as its not using ,= this would work on that data
var text = 'foo=bar, baz=quux',
pattern = new RegExp(/\b([^=,]+)=([^=,]+)\b/g),
obj = {};
while (match = pattern.exec(text)) obj[match[1]] = match[2];
console.dir(obj);
An alternate version of your updated solution that checks for the null/empty string and just returns an empty object and also allows for custom delimiters.
function stringToObject(str, delimiter) {
var result = {};
if (str && str.length > 0) {
str = str.split(delimiter || ',');
for (var i = 0; i < str.length; i++) {
var cur = str[i].split('=');
result[cur[0]] = cur[1];
}
}
return result;
}
first thing that occurred to me, I'll leave it as the original version, but cookies should not be empty otherwise there will be a json parse error
JSON.parse(`{"${document.cookie.replace(/=/g,'":"').replace(/; /g,'","')}"}`)
fast and reliable version - cookie to object
let c=document.cookie.split('; '),i=c.length,o={};
while(i--){let a=c[i].split('=');o[a[0]]=a[1]}
and short function for get single cookie
getCookie=e=>(e=document.cookie.match(e+'=([^;]+)'),e&&e[1])
function getCookie(){
var o=document.cookie.split("; ");
var r=[{}];
for(var i=0;i<o.length;i++){
r[o[i].split("=")[0]] = o[i].split("=")[1];
}
return r;
}
Just call getCookie() and it will return all cookies from the current website.
If you have a cookie called 'mycookie' you can run getCookie()['mycookie']; and it will return the value of the cookie 'mycookie'.
There is also a One-Line option:
function getCookie(){var o=document.cookie.split("; ");var r=[{}];for(var i=0;i<o.length;i++){r[o[i].split("=")[0]] = o[i].split("=")[1];}return r;}
This one can be used with the same methods as above.

find a specific string pattern in an array jquery

Apologies if this is a duplicate, but I can't seem to find the solution.
I am trying to find a specific string pattern in an array.
I want to find all values in data that contain 'underscore r underscore'. I then want to create a new array that contains only those keys and values.
var data = ["something", "bar_r_something"];
var resultArray = new Array();
for (var i = 0; i < data.length; i++) {
var bar = /_r_/;
if ($.inArray(bar, data[i].length) > 0)
{
console.log("found _r_");
resultArray.push(data[i]);
}
};
I just can't seem to get that $.inArray to work, it seems to always kick out -1.
var data = ["something", "bar_r_something"];
var resultArray = new Array();
for (var i = 0; i < data.length; i++) {
var bar = /_r_/;
if (bar.test(data[i])) {
alert("found _r_");
resultArray.push(data[i]);
}
};
console.log(resultArray);
Here you go, it doesn't use $.inArray, but Regex instead, hope that's cool!
EDIT
If you wanted to go a bit more fancy, you can use JavaScript's filter method like so:
var data = ["something", "bar_r_something"];
var resultArray = data.filter(function(d){
return /_r_/.test(d);
});
console.log(resultArray);
I think what you are looking for is $.grep(). Also $.inArray() does not test the values against a regex, it tests for equality.
var regex = /_r_/
var resultArray = $.grep(data, function(item){
return regex.test(item)
})
Demo: Fiddle

Extract specific substring using javascript?

If I have the following string:
mickey mouse WITH friend:goofy WITH pet:pluto
What is the best way in javascript to take that string and extract out all the "key:value" pairs into some object variable? The colon is the separator. Though I may or may not be able to guarantee the WITH will be there.
var array = str.match(/\w+\:\w+/g);
Then split each item in array using ":", to get the key value pairs.
Here is the code:
function getObject(str) {
var ar = str.match(/\w+\:\w+/g);
var outObj = {};
for (var i=0; i < ar.length; i++) {
var item = ar[i];
var s = item.split(":");
outObj[s[0]] = s[1];
}
return outObj;
}
myString.split(/\s+/).reduce(function(map, str) {
var parts = str.split(":");
if (parts.length > 1)
map[parts.shift()] = parts.join(":");
return map;
}, {});
Maybe something like
"mickey WITH friend:goofy WITH pet:pluto".split(":")
it will return the array, then Looping over the array.
The string pattern has to be consistent in one or the other way atleast.
Use split function of javascript and split by the word that occurs in common(our say space Atleast)
Then you need to split each of those by using : as key, and get the required values into an object.
Hope that's what you were long for.
You can do it this way for example:
var myString = "mickey WITH friend:goofy WITH pet:pluto";
function someName(str, separator) {
var arr = str.split(" "),
arr2 = [],
obj = {};
for(var i = 0, ilen = arr.length; i < ilen; i++) {
if ( arr[i].indexOf(separator) !== -1 ) {
arr2 = arr[i].split(separator);
obj[arr2[0]] = arr2[1];
}
}
return obj;
}
var x = someName(myString, ":");
console.log(x);

Javascript : String to a two dimesional Array

I have a javascript function which returns a string in the following format :
User,5
Group,6
I want this string to be converted into a two dimensional array like below, any idea how can I achieve it?
[['user,5],['Group',6]]
You have to split by line break or blank space and map to split by colon:
str.split("\n").map(function(e) { return e.split(',') });
EDIT: If you want the second one to be an integer, convert it using parseInt:
str.split("\n").map(function(e) {
var arr = e.split(',');
arr[1] = parseInt(arr[1], 10);
return arr;
});
Attention, you do have to have map installed for browsers that do not have support for ECMA Script 5 to maintain cross-browser compatibility. You can do that by adding this to your code
if (!('map' in Array.prototype)) {
Array.prototype.map= function(mapper, that /*opt*/) {
var other= new Array(this.length);
for (var i= 0, n= this.length; i<n; i++)
if (i in this)
other[i]= mapper.call(that, this[i], i, this);
return other;
};
}
var myBigString= " ";
var str1 =str.split("\n");
var myarr;
for(var i=0;i<str1.length;i++) {
var str2 =str.split(",");
for(var j=0;j<str2.length;j++) {
myarr[i] = str2[j]
}
}
USE STRING SPLIT BY COMMA AFTER THAT,FOR EXAMPLE
VAR STR11="User,5";
VAR STR22="GROUP,6";
VAR STR=STR11.split(",");
VAR STR1=STR22.split(",");
var items = [[STR[0],STR[1]],[STR1[0],STR1[1]]];
Try this
function convert(s) {
s.split("\n").map(function(s1){
var splits = s1.split(",")
splits[1] = parseInt(splits[1])
return splits
}
}
*assuming your string returned from function to be "User,5\nGroup,6"

Categories

Resources