JavaScript split and add a string - javascript

how to insert a string inside the url address after split ?
I have a simple code like this, but I just don't understand how split and join are work
I have tried "append" function but I can't get it right
I test and write it in
http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_split
<html>
<body>
<script type="text/javascript">
var str="/image/picture.jpg";
var test = str.split("/");
for(var i = 0; i < test.length; i++) {
document.write(test[1].join('/original') + "<br />");
}
document.write(test);
</script>
</body>
the output that I want is simply like this :
"/image/original/picture.jpg"
note: thanks for the help.

Just use replace instead:
str.replace('image/', 'image/original/');
if you really want to convert it into an array for some reason:
var ary = str.split('/');
ary.splice(2, 0, 'original');
ary.join('/');

vikenoshi,
You want to use the Array.splice method to insert new elements into your resulting array that you created using String.split. The splice method is documented here:
http://www.w3schools.com/jsref/jsref_splice.asp
Here is the code which should do what you want:
function spliceTest() {
var url = "/image/picture.jpg";
// split out all elements of the path.
var splitResult = url.split("/");
// Add "original" at index 2.
splitResult.splice(2, 0, "original");
// Create the final URL by joining all of the elements of the array
// into a string.
var finalUrl = splitResult.join("/");
alert(finalUrl); // alerts "/image/original/picture.jpg"
};
I created a JsFiddle with a working example:
http://jsfiddle.net/S2Axt/3/
A note about the other methods I'm using:
join: Join creates a new string from an array. This string is constructed by transforming all of the elements of the array into a string, and appending or concatenating them together. You can optionally provide a delimitter. Here I use the / to split the portions of the path.
split: Split splits a string based on another string into an array.

You could also do this:
var wholeURL = "/image/picture.jpg";
var choppedUpURL = wholeURL.split("/");
var finalURL = "/" + choppedUpURL[1] + "/original/" + choppedUpURL[2];
alert(finalURL);
http://jsfiddle.net/jasongennaro/KLZUT/

It's quick and simple
var str="/image/picture.jpg";
var elems = str.split("/");
elems.splice(elems.length-1, 0, "original")
document.write(elems.join("/");
Note I'm using the splice method with a first argument of the length of the array - 1. This puts the string "original" in the second to last position in the final path, not matter how long the URL you pass in. If this isn't the desired behavior, you can change the code to read elems.splice(2, 0, "original"). This would put the string "original" in the second position in the path, no matter how long the URL is.

Part of the problem with your code is that you're calling join on a string, not an array, see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/join.
The return type of split is an array, https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/split. So doing
var test = str.split("/");
means that test is an array. So then test[1] is a string of that array, and calling join on it won't work.

try:
var str="/image/picture.jpg";
var test = str.split("/");
test[3]=test[2];
test[2]='original';
document.write(test.join('/'));

Related

How to get string in path from split?

it didn't work on stackoverflow snippet but if you try on your local you will see it's going to work.
js give me a this result
cdn=//cdn.files.com/web
but I dont want to this line
cdn=
js must give me after from cdn= I mean result must be like this
//cdn.files.com/web
my all js is below so how to do that ?
var scripts = document.getElementsByTagName('script');
var index = scripts.length - 1;
var myScript = scripts[index];
// myScript now contains our script object
var queryString = myScript.src.replace(/^[^\=]+\??/,'');
alert(decodeURIComponent(queryString));
<script src="//domain.com/web/Assets/js/main.js?cdn=%2f%2fcdn.files.com%2fweb"></script>
<p></p>
var s = "cdn=//cdn.files.com/web";
s2 = s.substring(s.indexOf("cdn=")+4,s.length);
alert(s2);
this will substring from the index next to equals character to the end of yours string :)
fixed and tested
Split the string by '?cdn=' and get the part after that(second element in the result array, at index 1).
var queryString = myScript.src.split('?cdn=')[1];
FYI : If there is only one URL param then you can simply use = or cdn= for splitting.
You can use split:
yourvariable.split('=');
So whatever your arguments into GET, the odd param will get your desired result.
PS: Prefer just the = char, because you can work with whatever param you want into link gived by src.
why can't you use ^.+?cdn= in your regex?
this will give you strings after the cdn=
var myScript = '//domain.com/web/Assets/js/main.js?cdn=%2f%2fcdn.files.com%2fweb';
var queryString = myScript.replace(/^.+?cdn=/, '');
console.log(decodeURIComponent(queryString));
Solution with regex
var src = 'cdn=//cdn.files.com/web';
var url = src.replace(/^([^\=]+=)(.*)$/, '$2');
console.log(decodeURIComponent(url));
DEMO with explanation

Replace in javascript

I have a string something like this:
http://stackoverflow.com/questions/ask
And would like to return this part:
http://stackoverflow.com/questions/
How can I do this using pure javascript?
Thanks!
This will match and remove the last part of a string after the slash.
url = "http://stackoverflow.com/questions/ask"
base = url.replace(/[^/]*$/, "")
document.write(base)
Help from: http://www.regexr.com/
For slicing off last part:
var test = 'http://stackoverflow.com/questions/ask';
var last = test.lastIndexOf('/');
var result = test.substr(0, last+1);
document.write(result);
You can accomplish this with the .replace() method on String objects.
For example:
//Regex way
var x = "http://stackoverflow.com/questions/ask";
x = x.replace(/ask/, "");
//String way
x = x.replace('ask', "");
//x is now equal to the string "http://stackoverflow.com/questions/"
The replace method takes two parameters. The first is what to replace, which can either be a string or regex, literal or variable, and the second parameter is what to replace it with.

How to use split in javascript

I have a string like
/abc/def/hij/lmn.o // just a raw string for example dont know what would be the content
I want only /abc/def/hij part of string how do I do that.
I tried using .split() but did not get any solution.
If you want to remove the particular string /lmn.o, you can use replace function, like this
console.log(data.replace("/lmn.o", ""));
# /abc/def/hij
If you want to remove the last part after the /, you can do this
console.log("/" + data.split("/").slice(1, -1).join("/"));
# /abc/def/hij
you can do
var str = "/abc/def/hij/lmn.o";
var dirname = str.replace(/\/[^/]+$/, "");
Alternatively:
var dirname = str.split("/").slice(0, -1).join("/");
See the benchmarks
Using javascript
var x = '/abc/def/hij/lmn.o';
var y = x.substring(0,x.lastIndexOf("/"));
console.log(y);
var s= "/abc/def/hij/lmn.o"
var arr= s.split("/");
after this, use
arr.pop();
to remove the last content of the array which would be lmn.o, after which you can use
var new_s= arr.join("/");
to get /abc/def/hij

Convert string to Jquery dataset

I want to covert this string to jquery data table. I can't do this.
var str = "96,xxx,212,xxxx||
100,yyy,123,yyyy";
My original DataSet structure like this
var aDataSet = [['96','xxx','212','xxxx'],
['100','yyy','123','yyyy']];
This is my code what i tried;
var srchvalue = str.split('||');
for (var e = 0; e < srchvalue.length; e++) {
alert(srchvalue[e]);
aDataSet.push(srchvalue[e]);
}
But it's not convert the actual format.
You will just need to split() twice. You've done the first bit already. Then you will need to split the two strings in your array with the , as the separator.
You can use aDataSet.push(srchvalue[e].split(',')) inside the for loop you already have.
You are pushing in your array the result of a split on "||" which is a series of string like "96,xxx,212,xxxx". You need to split that string too in order to have a matrix:
[...]
aDataSet.push(srchvalue[e].split(','));
[...]
I got the solution, I used the below code to convert it.
var test = eval('[' + srchvalue[e].split(',') + ']');
aDataSet.push(test);

group parts of a string into an array element

If I have a string... abcdefghi
and I want to use regex to load every elemnent into an array but I want to be able to stick anything connected by plus sign into the same element... how to do that?
var mystring = "abc+d+efghi"
output array ["a","b","cde","f","g","h","i"]
One way to do it:
var re = /([^+])(?:\+[^+])*/g;
var str = 'abcd+e+fghi';
var a = str.match(re).map(function (s) { return s.replace(/\+/g, ''); });
console.log(a);
The value of a[3] should now be 'def'.
http://jsfiddle.net/rbFwR/2
You can use this expression, to produce [a][b][c+d+e][f][g][h][i].
mystring.split ("(.\+)*.")
Next, replace any + characters with empty on the resulting list.
mystring.split("\\+")
Click here for more information.

Categories