how to convert to array in js? - javascript

I have this string which I want to convert to an array:
var test = "{href:'one'},{href:'two'}";
So how can I convert this to an array?:
var new = [{href:'one'},{href:'two'}];

It depends where you got it from..
If possible you should correct it a bit to make it valid JSON syntax (at least in terms of the quotes)
var test = '{"href":"one"},{"href":"two"}';
var arr = JSON.parse('[' + test + ']');
Notice the " around both keys and values.
(making directly var test = '[{"href":"one"},{"href":"two"}]'; is even better)

If you could modify the original string to be valid JSON then you could do this:
JSON.parse(test)
Valid JSON:
var test = '[{"href":"one"},{"href":"two"}]';

Using jQuery:
var str = '{"id":1,"name":"Test1"},{"id":2,"name":"Test2"}';
var jsonObj = $.parseJSON('[' + str + ']');
jsonObj is your JSON object.

If changing the string to be valid JSON is not an option, and you fully trust this string, and its origin then I would use eval:
var test = "{href:'one'},{href:'two'}";
var arr = eval("[" + test + "]");
On that last note, please be aware that, if this string is coming from the user, it would be possible for them to pass in malicious code that eval will happily execute.
As an extremely trivial example, consider this
var test = "(function(){ window.jQuery = undefined; })()";
var arr = eval("[" + test + "]");
Bam, jQuery is wiped out.
Demonstrated here

Related

Javascript - Get substring that comes after "string1" and before "string2"

When making a fetch to a certain URL, I am getting an HTML page in the format of text as I wanted.
Inside of it, there are plenty of id=(...)" and I require one of them
So I am asking, how could I get an array with all the strings that come after "id=" and before the " " "?
I made some tries such as :
var startsWith = "id="
var endsWith = "\""
var between = fullString.slice(fullString.indexOf(startsWith), fullstring.indexOf(endsWith))
but couldn't get it to work.
Any suggestions are welcome
you can use the following regex: /id=\"(.*?)\"/gmi.
The code will be as such:
fullString.match(/id=\"(.*?)\"/gmi)
The result will be an array of id="your id"
and then you can do the following:
var between = fullString.match(/id=\"(.*?)\"/gmi).map(str => str.substr(str.indexOf('id=\"') + 'id=\"'.length).slice(0, -1))
Why you dont use a plugin like jquery? Please refer to this example:
var fullString = "<y>your cool html</y>";
var $html = $(fullString);
var stuffInside = $(html).find('#yourId');
console.warn('stuffInside:', stuffInside.html());

Removing https:// and .com from String

I am trying to convert a group of given URLs to another format I'll need in another part of the application.
So for the string https://www.myUrl.com/research/case-studies I need the following output:
myUrl/research/case studies
The following function I created manages just fine but I cannot help feeling I'm not being efficient enough by doing everything in just one line.
function generate_conversion(convert_input, url_format){
simple_urls = [];
var new_url = '';
$.each(convert_input, function(index, item) {
new_url = item.replace(/^(https?:\/\/)?(www\.)?(?:\.[a-z\.]+[\/]?)?/,'');
new_url = new_url.replace(/([.]\w+)$/, '');
new_url = new_url.replace(/.com/g, '');
simple_urls.push(new_url.replace(/-/g, ' '));
});
console.log(simple_urls);
}
Is there a more efficient or readable way to achieve the same result? I cannot use window.location.host or similar methods because the URLs are passed as simple strings.
depends on my understanding try this.,
var originalString="https://www.myUrl.com/research/case-studies";
var replacedString=originalString.replace("https://www.","")
console.log(replacedString);
Just do it
var str = "https://www.myUrl.com/research/case-studies";
var simple_url = str.substring(str.indexOf("www.")+4);
console.log(simple_url);

Javascript splitting string in to two parts number and text safely

I was wondering if there is a safe way (if the data is coming from users) to get the string and the number separated - for example "something-55", "something-124", "something-1291293"
I would want:
something and
55
something and
124
something and
1291293
I mean by a 'safe way' is to be certain I am getting only the number on the end.. if the data is coming from the users "something" could be anything some-thing-55 for example..
I'm looking for a robust way.
try this, working.
var string = 'something-456';
var array = string.split('-');
for (var i = 0;i<array.length;i++){
var number = parseFloat(array[i]);
if(!isNaN(number)){
var myNumber = number;
var mySomething = array[i - 1];
console.log('myNumber= ' + myNumber);
console.log('mySomething= ' + mySomething);
}
}
Can you try this?
var input='whatever-you-want-to-parse-324';
var sections=input.split(/[\w]+-/);
alert(sections[sections.length-1]);
You can use substr along with lastIndexOf:
var str = "something-somethingelse-55",
text = str.substr(0, str.lastIndexOf('-')),
number = str.substr(str.lastIndexOf('-') + 1);
console.log(text + " and " + number);
Fiddle Demo
All though it's a tad late, this would be the most restrictive solution:
var regex = /^([-\w])+?-(\d+)$/,
text = "foo-123",
match = test.match(regex);
You will get a match object back with the following values:
[ "foo-123", "foo", "123" ]
It's a very strict match so that " foo-123" and "foo-123 " would not match, and it requires the string to end in one or more digits.

Convert comma separated string to a JavaScript array

I have this string:
"'California',51.2154,-95.2135464,'data'"
I want to convert it into a JavaScript array like this:
var data = ['California',51.2154,-95.2135464,'data'];
How do I do this?
I don't have jQuery. And I don't want to use jQuery.
Try:
var initialString = "'California',51.2154,-95.2135464,'data'";
var dataArray = initialString .split(",");
Use the split function which is available for strings and convert the numbers to actual numbers, not strings.
var ar = "'California',51.2154,-95.2135464,'data'".split(",");
for (var i = ar.length; i--;) {
var tmp = parseFloat(ar[i]);
ar[i] = (!isNaN(tmp)) ? tmp : ar[i].replace(/['"]/g, "");
}
console.log(ar)
Beware, this will fail if your string contains arrays/objects.
Since you format almost conforms to JSON syntax you could do the following :
var dataArray = JSON.parse ('[' + initialString.replace (/'/g, '"') + ']');
That is add '[' and ']' characters to be beginning and end and replace all "'' characters with '"'. than perform a JSON parse.

Trimming a string from the end in Javascript

In Javascript, how can I trim a string by a number of characters from the end, append another string, and re-append the initially cut-off string again?
In particular, I have filename.png and want to turn it into filename-thumbnail.png.
I am looking for something along the lines of:
var sImage = "filename.png";
var sAppend = "-thumbnail";
var sThumbnail = magicHere(sImage, sAppend);
You can use .slice, which accepts negative indexes:
function insert(str, sub, pos) {
return str.slice(0, pos) + sub + str.slice(pos);
// "filename" + "-thumbnail" + ".png"
}
Usage:
insert("filename.png", "-thumbnail", -4); // insert at 4th from end
Try using a regular expression (Good documentation can be found at https://developer.mozilla.org/en/JavaScript/Guide/Regular_Expressions)
I haven't tested but try something like:
var re = /(.*)\.png$/;
var str = "filename.png";
var newstr = str.replace(re, "$1-thumbnail.png");
console.log(newstr);
I would use a regular expression to find the various parts of the filename and then rearrange and add strings as needed from there.
Something like this:
var file='filename.png';
var re1='((?:[a-z][a-z0-9_]*))';
var re2='.*?';
var re3='((?:[a-z][a-z0-9_]*))';
var p = new RegExp(re1+re2+re3,["i"]);
var m = p.exec(file);
if (m != null) {
var fileName=m[1];
var fileExtension=m[2];
}
That would give you your file's name in fileName and file's extension in fileExtension. From there you could append or prepend anything you want.
var newFile = fileName + '-thumbnail' + '.' + fileExtension;
Perhaps simpler than regular expressions, you could use lastindexof (see http://www.w3schools.com/jsref/jsref_lastindexof.asp) to find the file extension (look for the period - this allows for longer file extensions like .html), then use slice as suggested by pimvdb.
You could use a regular expression and do something like this:
var sImage = "filename.png";
var sAppend = "-thumbnail$1";
var rExtension = /(\.[\w\d]+)$/;
var sThumbnail = sImage.replace(rExtension, sAppend);
rExtension is a regular expression which looks for the extension, capturing it into $1. You'll see that $1 appears inside of sAppend, which means "put the extension here".
EDIT: This solution will work with any file extension of any length. See it in action here: http://jsfiddle.net/h4Qsv/

Categories