javascripttumblrtumblr-themes

Is it possible to change a certain string within an URL with another term using script?


Hi everyone.

I have a tumblr blog, whose navigation is organized in tags, forming URLs like these.

xxxx.com/home_english/

xxxx.com/home_spanish/

xxxx.com/news_english/

xxxx.com/news_english/chrono

xxxx.com/news_spanish/

xxxx.com/news_spanish/chrono

The blog has 2 links at the top that allow users to change the language of the blog. However, these links are static, pointing always to the homepage of the blog in the chosen language. 

My goal is to allow users to change the language any time while staying in the page that are currently visiting, being capable for example, and by clicking only the aforementioned links, to go directly from... 

xxxx.com/news_english/chrono to...
xxxx.com/news_spanish/chrono. 

I guess the script should then be able to grab the current URL, find the string associated with the language (always after the unique underscore of the URL, sometimes before the second dash after the domain, sometimes not), then substitute it by the target language and finally rebuild the URL.

That’s it. Thank you so much.

Regards


Solution

  • After you've created an string out of your url as Simone said in his comment, you should find the ${pageName}_${languageName} word; Based on the details you've provided, you can do it like this:

    // creating an string out of url; Note that you should define createUrlString function yourself
    const urlString = createUrlString(url);
    
    //finding the page_language word in the string
    const wordsArray = urlString.split('/');
    const pageLanguage = wordsArray.find(word => word.includes('_'))
    
    

    After this step, you can easily change the 'pageLanguage' word by replacing current language with the selected one, and then replace it in the url string.