Split string in Javascript with _ - javascript

I am beginner with javascript.I want to create array as 1,2,3,4,5
But I get o/p as ,1,2,3,4,5
I tried with .split() in javascript but I am not getting the required output.
var string="testrating_1testrating_2testrating_3testrating_4testrating_5";
var temp = new Array();
temp = string.split("testrating_");
for (a in temp ) {
temp[a] = temp[a];
}
fiddle

You could do it this way:
var string = "testrating_1testrating_2testrating_3testrating_4testrating_5",
temp = string.split('testrating_');
temp.shift(); //remove fist item which is empty
console.log(temp); //["1", "2", "3", "4", "5"]

The actual value of temp is ["","1","2","3","4","5"]. This is happening because of .split and the string starting with the delimiter.
If you always know the delimiter will be at the start of the string, you can do this, which removes the first element of the Array:
temp = string.split("testrating_").slice(1);

You can try this...
<!DOCTYPE html>
<body>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
var string="testrating_1testrating_2testrating_3testrating_4testrating_5";
var temp = [];
temp = string.split("testrating_");
var tempNew=[];
for (a in temp ) {
if(temp[a]!==''){
tempNew.push(temp[a]);
}
}
alert(tempNew);
}
</script>
</body>
</html>
JSFiddle

You are getting ,1,2,3,4,5 because there is no character at the beginning of the string before testrating_ by which you are separating.
either you can remove testrating_ from first position like statement below
var str="1testrating_2testrating_3testrating_4testrating_5";
str.split("testrating_")
Or you can remove character from first index after getting result as from array
var str="testrating_1testrating_2testrating_3testrating_4testrating_5";
str.split("testrating_").slice(1);

Do this:
<!DOCTYPE html>
<body>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
var string="testrating_1testrating_2testrating_3testrating_4testrating_5";
var temp = new Array();
temp = string.split("testrating_");
var output = new Array();
for (x = 0; x < temp.length; x++) {
output[x - 1] = temp[x];
}
alert(output);
}
</script>
</body>
</html>

You could always use .splice:
var string="testrating_1testrating_2testrating_3testrating_4testrating_5";
temp = string.split("testrating_"); // temp = ["","1","2","3","4","5"]
temp.splice(0,1) // temp = ["1","2","3","4","5"]
What splice does here is goes to the first value in the array (index #0) and removes one value from that point which would be the empty string "".
To give a little more of an explanation, you could remove the empty string and "1" by using splice like so:
temp.splice(0,2) // temp = ["2","3","4","5"]
Keep in mind that splice directly effects the array it's called upon and returns an array of values that were removed. So if you did the following:
values = temp.splice(0,2) // values=["","1"] temp=["2","3","4","5"]
Also, in this example creating a new array in the following fashion temp = new Array(); is redundant since string.split() effectively creates an array and fills it with the values that were splitted. Keep that in mind going forward. Hope this helps and welcome to the world of programming!

var string="testrating_1testrating_2testrating_3testrating_4testrating_5";
// Split and remove first entry and return an array
var final = string.split("testrating_").slice(1);
$('#out').text(JSON.stringify(final));

Try this:
var string = "testrating_1testrating_2testrating_3testrating_4testrating_5";
var temp = string.split("testrating_").join("").split("").join();
console.log(temp);
Can also be done like this:
var temp = string.replace(/testrating_/g,"").split("").join();
or just:
var string = "testrating_1testrating_2testrating_3testrating_4testrating_5";
var temp = string.match(/[\d]/g); //your regex here
console.log(temp);
Not sure about the performance though.

Related

How do I show only numbers from a Javascript array that has both numbers and letters use parseInt?

I'm trying to use the parseInt to show only numbers from the following array:
1,2,a,b
Here is my javascript code so far:
var filter_list = ["1,2,a,b"];
function myFunction() {
parseInt(filter_list);
return filter_list;
}
document.getElementById("display").innerHTML = filter_list;
Maybe my idea isn't even going to work. Would love some feedback.
You have array with one element that is string, so you could use join and split and then filter method.
var data = ["1,2,a,b"];
var numbers = data.join(",").split(",").filter(Number);
console.log(numbers)
First, you have to know that each element of the array has to have teir own " ". Like that:
var filter_list = ["1","2","a","b"];
then, if you want to know the elements that are numbres, you can do something like that:
var filter_list = ["1","2","a","b"];
for(i = 0; i < filter_list.length; i++ {
if (!isNaN(ParseInt(filter_list[i])){
var new_array = [];
new_array[i] = filter_list[i];
}
}
document.getElementById("display").innerHTML = new_array;
I don't know if is that what you wanted to know.

How to insert two value in one time to array using JavaScript

I want to insert two values in one array in each loop. I have tried
feature_arr = [];
$form.find( '.variations .value' ).each( function() {
var $radios = $( this ).find( 'input[type=radio]' );
var $checked_radio = $radios.filter(':checked');
var attribute_name = $radios.attr( 'name' );
feature_arr[] = attribute_name1;
feature_arr[] = $checked_radio.val();
});
I want array this form ["1", "Brighton_Black", "2", "Frame_Base", "3", "Matching_upholstery", "6", "Headrest", "7", "Covered"]
But give me error this code
try this
var feature_arr = new Array(); // define the array or you can use feature_arr = []
and inside your condition
feature_arr.push(your_value_1);
feature_arr.push(your_value_2);
for the second part for your question in the comment try this
<html>
<head></head>
<title></title>
<style type="text/css">
</style>
<body>
</body>
<script type="text/javascript">
var thestring = "matching_upholstery";// this is your string
alert(toupper(thestring)); // in here we pass out string to the method/function we wrote that returns the converted output string. to see the result we use an alert here.
//this is the function that convert the first letter to upper and return the final result
function toupper(a)
{
var stringArray = a.split('_');//split your word from '_' character.
var firstword = stringArray[0];//get the first word
var firstwordWithupper = firstword.charAt(0).toUpperCase()+firstword.slice(1);//convert the first letter to upper
var secondword = stringArray[1]; // get the second word
var secondwordWithupper = secondword.charAt(0).toUpperCase()+secondword.slice(1);//convert the first letter of second word to upper
var finalresult = firstwordWithupper +"_"+secondwordWithupper;
return finalresult;
}
</script>
</html>
you can also do like
var a = [].concat(1,2);
in one line. In your case inside the condition you can do like
feature_arr = feature_arr.concat(value1,value2)
or if you receive your multiple data in an array this would result the same
feature_arr = feature_arr.concat([value1,value2])

Javascript creating arrays from strings

I have following code:
var selector="a,b,c/m,n",
property = "width,height/font-size";
I want to group each set of strings (separated by forward slash) to new array.
so I would (basically) end up with this:
var selector_array1 = [a,b,c];
var selector_array2 = [m,n];
----
var property_array1 = [width,height];
var property_array2 = [font-size];
....
so I would end up with 2 for loops (I think), like:
for(outer loop){//for each selector array
for(inner loop){//for each item in selector array apply each property in property array
}
}
Bear in mind it can only have 1 value/property like (so no forward slashes to split):
var selector="a/m",
property = "width/font-size";
or like this:
var selector="a",
property = "width";
You can still use split on the ones with no slashes. Just split once on slashes then split those results on commas.
function extractData(input) {
// Separate by /'s
return input.split('/')
.map(function(str) {
// For each of the new strings, split them on commas
return str.split(',');
});
}
var data = extractData('a,b,c/width,height');
console.log(data[0].toString(), '|', data[1].toString());
data = extractData('a,b,c');
console.log(data[0].toString());
data = extractData('a/width,height');
console.log(data[0].toString(), '|', data[1].toString());
data = extractData('a/width');
console.log(data[0].toString(), '|', data[1].toString());
To do that you need to use the split method of the String prototype:
var selector="a,b,c/m,n",
property = "width,height/font-size";
function splitString(s){
// Split the string with the character /
// And loop through the array
return s.split('/').map(function(stringWithComa){
// Return the result of the string split
return stringWithComa.split(',')
})
}
console.log(splitString(selector));
console.log(splitString(property));
Hope it helps ;) Dont hesitate to ask question ;)
Here is an method using split() and arrays.
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<script type="text/javascript">
var selector="a,b,c/m,n";
var property = "width,height/font-size";
var selector_array1 = new Array();
var selector_array2 = new Array();
var property_array1;
var property_array2;
var selectors = selector.split('/');
var properties = property.split('/');
for(var i = 0; i<selectors.length; i++) {
selectors[i] = selectors[i].split(',');
for(var j = 0; j<selectors[i].length;j++) {
if(i==0)
selector_array1.push(selectors[i][j])
else
selector_array2.push(selectors[i][j])
}
}
alert(selector_array1);
alert(selector_array2);
</script>
</body>
</html>

Replace one string within array

I have the following array:
etst,tset,tets,ttest,teest,tesst,testt,4est,test,dest
I want to delete the value of an input box from the array, here's what I'm trying:
var el = document.getElementById('searchInput').value; // this is "test"
var toSearchFor = eld.slice(0,10); // the array above
for(var i=0; i < toSearchFor.length; i++) {
toSearchFor[i] = toSearchFor[i].replace(/el/g, "");
}
It's simply not replacing "test" with ""
How can I do that?
You can use Array.filter (see MDN) to filter out the desired value:
var arr = 'etst,tset,tets,ttest,teest,tesst,testt,4est,test,dest'.split(',')
,val = 'test'
document.querySelector('#result')
.innerHTML = arr.filter(function (v) {return v != val});
<div id="result"></div>
A text field example in this jsFiddle
for global replacement of a string stored in a variable u need to create an instance of RegExp explicitly, like this:
var regex = new RegExp(el, "g");
then use it in replace function:
toSearchFor[i] = toSearchFor[i].replace(regex, "");
The problem with your code is in your regular expression: /el/g. This is trying to match the letters el, instead of whatever it's in the el variable. You could have done it using the RegExp construtor.
// ...
regexp = new RegExp(el); // No need to use 'g' here since you're looking for the whole word
toSearchFor[i] = toSearchFor[i].replace(regexp, "");
// ...
Here's another way of doing it:
var eld = ['etst','tset','tets','ttest','teest','tesst','testt','4est','test','dest'];
// var el = document.getElementById('searchInput').value;
var el = 'test';
console.log(eld);
var index = eld.indexOf(el);
if (index >= 0) {
eld[index] = '';
}
console.log(eld);
Here's the output:
["etst", "tset", "tets", "ttest", "teest", "tesst", "testt", "4est", "test", "dest"]
["etst", "tset", "tets", "ttest", "teest", "tesst", "testt", "4est", "", "dest"]
In this case, we're using Array.prototype.indexOf, which returns the first index at which a given element can be found in the array, so that we can access that element directly (if found).
I hope that helps!

How to extract values from a string in javascript?

I need some help with extracting values from a cookie using javascript.
The string in a cookie looks something like this:
string = 'id=1||price=500||name=Item name||shipping=0||quantity=2++id=2||price=1500||name=Some other name||shipping=10||quantity=2'
By using string.split() and string.replace() and a some ugly looking code I've somehow managed to get the values i need (price, name, shipping, quantity). But the problem is that sometimes not all of the strings in the cookie are the same. Sometimes the sting in a cookie will look something like this :
string = 'id=c1||color=red||size=XL||price=500||name=Item name||shipping=0||quantity=2++id=c1||price=500||name=Item name||shipping=0||quantity=2'
with some items having color and size as parameters and sometimes only one of those.
Is there some more efficient way to explain to my computer that i want the part of the string after 'price=' to be a variable named 'price' etc.
I hope I'm making sense I've tried to be as precise as I could.
Anyway, thank you for any help
EDIT: I just wanted to say thanks to all the great people of StackOverflow for such wonderfull ideas. Because of all of your great suggestions I'm going out to get drunk tonight. Thank you all :)
Let's write a parser!
function parse(input)
{
function parseSingle(input)
{
var parts = input.split('||'),
part,
record = {};
for (var i=0; i<parts.length; i++)
{
part = parts[i].split('=');
record[part[0]] = part[1];
}
return record;
}
var parts = input.split('++'),
records = [];
for (var i=0; i<parts.length; i++)
{
records.push(parseSingle(parts[i]));
}
return records;
}
Usage:
var string = 'id=1||price=500||name=Item name||shipping=0||quantity=2++id=2||price=1500||name=Some other name||shipping=10||quantity=2';
var parsed = parse(string);
/* parsed is:
[{id: "1", price: "500", name: "Item name", shipping: "0", quantity: "2"},
{id: "2", price: "1500", name: "Some other name", shipping: "10", quantity: "2"}]
*/
You can achieve this using regular expressions. For example, the regex /price=([0-9]+)/ will match price=XXX where XXX is one or more numbers. As this part of the regex is surrounded by parenthesis it explicitly captures the numeric part for you.
var string = 'id=1||price=500||name=Item name||shipping=0||quantity=2++id=2||price=1500||name=Some other name||shipping=10||quantity=2'
var priceRegex = /price=([0-9]+)/
var match = string.match(priceRegex);
console.log(match[1]); // writes 500 to the console log
Try that:
var string = 'id=1||price=500||name=Item name||shipping=0||quantity=2++id=2||price=1500||name=Some other name||shipping=10||quantity=2';
var obj = new Array();
var arr = string.split('||');
for(var x=0; x<arr.length;x++){
var temp = arr[x].split('=');
obj[temp[0]] = temp[1]
}
alert(obj['id']); // alert 1
First, split your string into two (or more) parts by ++ separator:
var strings = myString.split('++');
then for each of the strings you want an object, right? So you need to have an array and fill it like that:
var objects = [];
for (var i = 0; i < strings.length; ++i) {
var properties = strings[i].split('||');
var obj = {};
for (var j = 0; j < properties.length; ++j) {
var prop = properties[j].split('=');
obj[prop[0]] = prop[1]; //here you add property to your object, no matter what its name is
}
objects.push(obj);
}
thus you have an array of all objects constructed from your string. Naturally, in real life I'd add some checks that strings indeed satisfy the format etc. But the idea is clear, I hope.
If you can replace the || with &, you could try to parse it as if it were a query string.
A personal note - JSON-formatted data would've been easier to work with.
I would attach the data to a javascript object.
var settingsObj = {};
var components = thatString.split('||');
for(var j = 0; j < components.length; j++)
{
var keyValue = components[j].split('=');
settingsObj[keyValue[0]] = keyValue[1];
}
// Now the key value pairs have been set, you can simply request them
var id = settingsObj.id; // 1 or c1
var name = settingsObj.name; // Item Name, etc
You're already using .split() to break down the string by || just take that a step further and split each of those sections by = and assign everything on the left the field and the right the value
This should get the first match in the string:
string.match(/price=(\d{1,})/)[1]
Note this will only match the first price= in the string, not the second one.
If you can use jQuery, it wraps working with cookies and lets you access them like:
Reading a cookie:
var comments = $.cookie('comments');
Writing a cookie:
$.cookie('comments', 'expanded');
This post by someone else has a decent example:
http://www.vagrantradio.com/2009/10/getting-and-setting-cookies-with-jquery.html
If you can't use jQuery, you need to do standard string parsing like you currently are (perhaps regular expressions instead of the string splitting / replacing might trim down your code) or find some other javascript library that you can use.
If you like eye candies in your code you can use a regexp based "search and don't replace" trick by John Resig (cached here) :
var extract = function(string) {
var o = {};
string.replace(/(.*?)=(.*?)(?:\|\||$)/g, function(all, key, value) {
o[key] = value;
});
return o;
};
Then
var objects = string.split('++'),
i = objects.length;
for (;i--;) {
objects[i] = extract(objects[i]);
}
You could do something like this, where you eval the strings when you split them.
<html>
<head>
<script type="text/javascript">
var string = 'id=c1||color=red||size=XL||price=500||name=Item name||shipping=0||quantity=2++id=c1||price=500||name=Item name||shipping=0||quantity=2'
var mySplitResult = string.split("||");
for(i = 0; i < mySplitResult.length; i++){
document.write("<br /> Element " + i + " = " + mySplitResult[i]);
var assignment = mySplitResult[i].split("=");
eval(assignment[0] + "=" + "\""+assignment[1]+"\"");
}
document.write("Price : " + price);
</script>
</head>
<body>
</body>
</html>
var str = 'id=c1||color=red||size=XL||price=500||name=Item name||shipping=0||quantity=2++id=c1||price=500||name=Item name||shipping=0||quantity=2'
var items = str.split("++");
for (var i=0; i<items.length; i++) {
var data = items[i].split("||");
for (var j=0; j<data.length; j++) {
var stuff = data[j].split("=");
var n = stuff[0];
var v = stuff[1];
eval("var "+n+"='"+v+"'");
}
alert(id);
}
EDIT: As per JamieC's suggestion, you can eliminate eval("var "+n+"='"+v+"'"); and replace it with the (somewhat) safer window[n] = v; -- but you still have the simple problem that this will overwrite existing variables, not to mention you can't tell if the variable color was set on this iteration or if this one skipped it and the last one set it. Creating an empty object before the loop and populating it inside the loop (like every other answer suggests) is a better approach in almost every way.
JSON.parse('[{' + string.replace(/\+\+/g, '},{').replace(/(\w*)=([\w\s]*)/g, '"$1":"$2"').replace(/\|\|/g, ',') + '}]')
Convert the string for JSON format, then parse it.

Categories