javascript函数替换不起作用,为什么

javascript function replace wont work , why?

本文关键字:为什么 不起作用 替换 函数 javascript      更新时间:2023-09-26

为什么javascript函数替换不起作用?

    social_share: function(e){
        var is_video,
            social_name = $(e).attr('class'),
            share_url = document.URL,
            share_title = $('title').text(),
            share_media,
            share;
        switch(social_name) {
            case 'twitter':
                share = 'https://twitter.com/share?url={share_url}&text={share_title}';
            break;
            case 'facebook':
                share = 'https://www.facebook.com/dialog/feed?app_id=123050457758183&link={share_url}&picture={share_media}&name={share_title}';
            break;
            case 'google':
                share = 'https://plus.google.com/share?url={share_url}';
            break;
            case 'pinterest':
                share = 'https://pinterest.com/pin/create/bookmarklet/?media={share_media}&url={share_url}&is_video={is_video}&description={share_title}';
            break;
            case 'mailto':
                share = '...';
            break;
        }
        share.replace('{share_title}', share_title)
             .replace('{share_url}', encodeURI(share_url))
             .replace('{share_media}', encodeURI(share_media))
             .replace('{is_video}', is_video);
        console.log(share);
    },

和console.log函数返回字符串share而不进行任何替换。。。它会https://twitter.com/share?url={share_url}&text={share_title}如果是twitter,则相同的其他

.replace将返回新值,因此需要将其保存到变量:

share = share.replace( ... )

字符串在javascript中是不可变的。因此,通过任何字符串函数更改字符串都将返回一个新字符串作为输出。在上面的代码中,将语法更改为:

share = share.replace('{share_title}', share_title);