JavaScript split and add a string

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/

    链接地址: http://www.djcxy.com/p/74988.html

    上一篇: 为什么JavaScript声明变量在初始化之前在全局对象中?

    下一篇: JavaScript分割并添加一个字符串