producing a word from a string in javascript - javascript

I have a string which is name=noazet difficulty=easy and I want to produce the two words noazet and easy. How can I do this in JavaScript?
I tried var s = word.split("=");
but it doesn't give me what I want .

In this case, you can do it with that split:
var s = "name=noazet difficulty=easy";
var arr = s.split('=');
var name = arr[0]; //= "name"
var easy = arr[2]; //= "easy"
here, s.split('=') returns an array:
["name","noazet difficulty","easy"]

you can try following code:
word.split(' ').map(function(part){return part.split('=')[1];});
it will return an array of two elements, first of which is name ("noazet") and second is difficulty ("easy"):
["noazet", "easy"]

word.split("=") will give you an array of strings which are created by cutting the input along the "=" character, in your case:
results = [name,noazet,difficulty,easy]
if you want to access noazet and easy, these are indices 1 and 3, ie.
results[1] //which is "noazet"
(EDIT: if you have a space in your input, as it just appeared in your edit, then you need to split by an empty string first - " ")
Based on your data structure, I'd expect the desired data to be always available in the odd numbered indices - but first of all I'd advise using a different data representation. Where is this string word coming from, user input?

Just as an aside, a better idea than making an array out of your input might be to map it into an object. For example:
var s = "name=noazet difficulty=easy";
var obj = s.split(" ").reduce(function(c,n) {
var a = n.split("=");
c[a[0]] = a[1];
return c;
}, {});
This will give you an object that looks like this:
{
name: "noazert",
difficulty: "easy"
}
Which makes getting the right values really easy:
var difficulty = obj.difficulty; // or obj["difficulty"];
And this is more robust since you don't need to hard code array indexes or worry about what happens if you set an input string where the keys are reversed, for example:
var s = "difficulty=easy name=noazet";
Will produce an equivalent object, but would break your code if you hard coded array indexes.

You may be able to get away with splitting it twice: first on spaces, then on equals signs. This would be one way to do that:
function parsePairs(s) {
return s.split(' ').reduce(
function (dict, pair) {
var parts = pair.split('=');
dict[parts[0]] = parts.slice(1).join('=');
return dict;
},
{}
);
}
This gets you an object with keys equal to the first part of each pair (before the =), and values equal to the second part of each pair (after the =). If a string has multiple equal signs, only the first one is used to obtain the key; the rest become part of the value. For your example, it returns {"name":"noazet", "difficulty":"hard"}. From there, getting the values is easy.
The magic happens in the Array.prototype.reduce callback. We've used String.prototype.split to get each name=value pair already, so we split that on equal signs. The first string from the split becomes the key, and then we join the rest of the parts with an = sign. That way, everything after the first = gets included in the value; if we didn't do that, then an = in the value would get cut off, as would everything after it.
Depending on the browsers you need to support, you may have to polyfill Array.prototype.reduce, but polyfills for that are everywhere.

Related

Storing the word length in javascript array

I am puzzled as to why I can not store the word length in a javascript array.
I have tried
var i = [];
i["length"] = "ABC";
i["len"+"gth"] = "ABC";
but both aren't accepted in javascript. Can anyone explain it, and is there a way that I can store the word length in an array as above.
Since some asked for more detail. I am creating a list of words that I need to do a lookup at and find the value to display to the user. My list contains for example:
localVars.FunctionDic = [];
localVars.FunctionDic["lastindexof"] = "LastIndexOf(text, textToLocate)";
localVars.FunctionDic["specificindexof"] = "SpecificIndexOf(text, textToLocate, indexNumber)";
localVars.FunctionDic["empty"] = "Empty(text)";
localVars.FunctionDic["length"] = "Length(text)";
everything works except for the "length"
and I am using an array since I need to test if the word a user search for is in my array, and if it is display the value, if it is not, show nothing
It does not work because you are trying to write a string to a property that only allows a number.
From MDN: The length property of an object which is an instance of type Array sets or returns the number of elements in that array. The value is an unsigned, 32-bit integer that is always numerically greater than the highest index in the array.
With the limited details in your question it is hard to tell what you are actually trying to accomplish. It seems like you want to use an array like an object. If that is the case, use an object.
var i = {};
i["length"] = "ABC";
Based on the expected output, I believe you should be using an object not an array.
const FunctionDic = {
lastindexof: "LastIndexOf(text, textToLocate)",
specificindexof: "SpecificIndexOf(text, textToLocate, indexNumber)",
empty: "Empty(text)",
length: "Length(text)",
};
console.log(FunctionDic["lastindexof"]);
console.log(FunctionDic["specificindexof"]);
console.log(FunctionDic["empty"]);
console.log(FunctionDic["length"]);
To store the word length in an array you can do:
var i = ["length"]
If you want to store the length of a word in an array you can do:
var lengthOfHello = "hello".length
var i = [lengthOfHello]
var i = ["ABC"];
console.log(new Array(i[0].length).length);

Sending an array with JavaScript to the next page

The combination of my methods of declaring an array, adding elements to the array and applying the method toString() does not work. Essentially I enter a certain number (between one and five) values to textvariables : fontVorto1, fontVorto2, fontVorto3 ……… in the html-part of the document.
When I decide on leaving the remaining textelements empty, I click on a button, to assign them to an array, by way of the following function:
function difinNombroFv () {
var fontVortoj = new array();
fontVortoj[0] = document.getElementsByName("fontVorto1")[0].value;
fontVortoj[1] = document.getElementsByName("fontVorto2")[0].value;
fontVortoj[2] = document.getElementsByName("fontVorto3")[0].value;
……………….
and put them together in a string:
x = fontVortoj.toString();
document.getElementsByName("fontVorto")[0].value = x;
(the extra variable x is not needed) to enable me sending them to the next document, where I want to unserialize them with
$fontVortoj = unserialize($_POST["fontVorto"]);
I tested the method toString() by insering an alert(x), but the result was that I got for x the value of "fontVorto1" only.
I met solutions with JSON, jQuery etc., but I never used those "languages", only HTML, JavaScript, PHP.
Will my Christmas day be spoiled because of this simple problem ;>)?
couple of things to note:
1. var fontVortoj = new array(); . here new array() is not correct. it should be:
var fontVortoj = new Array();
now if you call fontVortoj.toString(), then it will convert the array and return a string with array elements separated by comma.
you can rebuild the array from the string in php by using "explode" function.
you can rebuild the array from the string in javascript by using "split" function.
Apparently I misunderstood the question to begin with.
To serialize an astray, you can use .join()
By default, it will give you the values, joined by commas.
To deserialize, use .split()
If there's a chance that there might be commas in your values, choose a more elaborate string for joining:
var ar = ["a", "b"];
var serialized = ar.join("|"); // "a|b"
var deserialized = serialized.split("|"); //["a", "b"]
The string that you use for joining and splitting can be as long as you like.
If you want to be completely covered against any values, then you need to look at JSON.stringify() & JSON.parse(). But that had browser compatibility issues.

String manipulation - removing an element from a list

I have a comma separated list of values, and I need to remove the one that is equal to a certain value.
myList = '10,20,30';
myList.remove(20); // === '10,30'
I'm dashing off, but the component parts of the solution will probably be:
String#split, which splits a string into an array based on a delimiter.
Array#indexOf, which finds an entry in an array (some older browsers may not have it; on those, you'll have to do a loop).
Array#splice, which (amongst other things) removes entries from an array.
Array#join, which joins an array into a string using a given delimiter.
...possibly with something mixed in there to deal with stray spaces, if they're a possibility.
Or of course, you could just put commas at either end and then search for ",20," with String#indexOf and use String#substring to grab the bits in front of and behind it. But what fun is that. ;-) (And it seems a bit fragile.)
Here is some tested and jslinted code that does what you're asking for.
if (!String.prototype.removeListItem) {
String.prototype.removeListItem = function(value, delimiter) {
delimiter = delimiter || ',';
value = value.toString();
var arr = this.split(delimiter),
index = arr.indexOf(value);
while (index >= 0) {
arr.splice(index, 1);
index = arr.indexOf(value);
}
return arr.join(delimiter);
};
}
alert('10,20,30,120,200'.removeListItem(20));
// yields '10,30,120,200'
However, I question why you would do this. Arrays should be stored in array objects, not in string literals. If you need to display the list, then convert to a delimited list at display time. If your input is a string, then split it at input time and keep it internally as an array. I really strongly believe this is the best practice for you and in the long run you will have much easier to maintain code that is much easier to understand.
var myArray = myList.split(',');
myArray.splice(1,1); // Remove one element at index 1, which is 20 in your example
myList = myArray.toString();
A few people almost had replace working.
var lists = ['20', '10,20', '20,30', '10,20,30', '120,200,2020'];
for (var i=0; i<lists.length; ++i) {
lists[i] = lists[i].replace(/(^|,)20,|(^|,)20$/,'$1');
}
Result:
["", "10", "30", "10,30", "120,200,2020"]
Split the string to give you an array. Once you have it in an array, remove the element you need removed. Then output the string again.
Or you could find and replace '20', with ''.

building a search from split(": ") and indexing it into object

In the below javascript, "this" refers to Car object and search_id refers to the input text field with an id of "search_input". So basically the user types in text in the field and a search occurs based on the input. Now I understand that the val() method is grabbing the user input string from the input field. However, I am not sure what the colon in the split() method is doing. I always thought the split() method just puts a comma delimiter when you pass in an empty string into it. And then it appears that the splitted variable holds an array of strings broken down from the input. However, why would we be passing in the first broken down string in the string array (splitted[0]) and the second string (splitted[1]) and then passing that into the variable string_to_scope? Basically it is in the process of building a search. And it's these three lines I'm not sure what's going on:
var splitted = jQuery(this.search_id).val().split(": ");
if (splitted[0] && splitted[1]){
if (string_to_scope[splitted[0]]) ret[string_to_scope[splitted[0]]] = splitted[1];
Here's more context:
Car.prototype.filter_func=function(){
var ret={};
var string_to_scope = {
'Year': 'year_num_eq',
'Make': 'make_name_eq',
'Description': 'description_eq',
'Expiry': 'expires_on_eq'
};
var search_value = jQuery(this.search_id).val();
if(search_value != null && search_value.length > 0){
var splitted = jQuery(this.search_id).val().split(": ");
if (splitted[0] && splitted[1]){
if (string_to_scope[splitted[0]]) ret[string_to_scope[splitted[0]]] = splitted[1];
}
}
return ret;
};
Thanks for any response.
// 'Year: 1998' -> ['Year', '1998'];
var splitted = jQuery(this.search_id).val().split(": ");
// if there were two parts
// (the year is not missing)
if (splitted[0] && splitted[1]){
// if the key exists in string_to_scope object
// -> ok because string_to_scope['Year'] exists
if (string_to_scope[splitted[0]])
// ret[ string_to_scope['Year'] ]
// -> ret['year_num_eq'] = '1998';
ret[ string_to_scope[splitted[0] ] = splitted[1];
The idea is to allow someone to enter a search that looks like "Make: Toyota". That is to say, to make a single search box accommodate searches across multiple fields (where you specify which field). A more typical approach would be to have a drop-down for search type that is separate from the search term; this is trying to combine them into one box.
The "split" method takes a string that contains a delimiter and turns it into an array that contains everything before, between, or after the delimiter. In this case it's turning
"Make: Toyota" into ["Make","Toyota"].
The first piece (the search type) becomes the key into the scope hash, and the second piece becomes the search term.
Split does just like it sounds. Splits a string by the input and returns an array. So that is what is happening with the split.
jQuery(this.search_id).val().split(": ");
Then they are checking if there are values set for both the first index and the second.
if (splitted[0] && splitted[1])
If that is true then they are checking if the first value matches the name of a property in the string_to_scope object. You can access object properties by index similar to an array.
if (string_to_scope[splitted[0]])
If there is a property by that name then they are returning a new object ret with a property of the first split value that equals the second split value.
ret[string_to_scope[splitted[0]]] = splitted[1];

How to manipulate string in an array

I have an array that contain some fields
like this
ctl00_ctl00_cphBody_bodycph_content_rdo_SID_25_SortOrder_17
ctl00_ctl00_cphBody_bodycph_content_rdo_SID_25_SortOrder_18
ctl00_ctl00_cphBody_bodycph_content_rdo_SID_25_SortOrder_19
I want to create a new array or manipulate this array to contain only
sid = {25,26,27}
from
_SID_25
_SID_26
_SID_27
where sid will be my array containing sid's extracted from above array
with pattern _SID_
I have to do this in jquery or javascript
use jquery map + regexp
var arr= ['tl00_ctl00_cphBody_bodycph_content_rdo_SID_25_SortOrder_17',
'ctl00_ctl00_cphBody_bodycph_content_rdo_SID_26_SortOrder_18',
'ctl00_ctl00_cphBody_bodycph_content_rdo_SID_27_SortOrder_19']
var out = $(arr).map(function(){
return this.match(/SID_(.*?)_/)[1];
});
out should be an array of the values..
(assuming all the values in the array do match the pattern)
I would use regex here
var sid = []
var matches = "ctl00_ctl00_cphBody_bodycph_content_rdo_SID_25_SortOrder_17".match(/_SID_(\d+)/);
if(matches) sid.push(parseInt(matches[1]));
This solution is totally reliant on the overall string form not changing too much, ie the number of "underscores" not changing which seems fragile, props given to commenter below but he had the index wrong. My original solution first split on "SID_" since that seemed more like a key that would always be present in the string going forward.
Given:
s = "ctl00_ctl00_cphBody_bodycph_content_rdo_SID_25344_SortOrder_17"
old solution:
array.push(parseInt(s.split("SID_")[1].split("_")[0]))
new solution
array.push(parseInt(s.split("_")[7])

Categories

Resources