jQuery: Add a String to URL

2019-08-03 22:50发布

I'm using this snippet of code to grab a url from a clicked link:

var url = $(this).find('a').attr('href');

I want to add a string to that url.

For example, my current url is:

http://mydomain.com/myarticle

I want to make it:

http://mydomain.com/myarticle-chinese

What should I add to my initial line of code to make that happen?

I'd be grateful for your advice!

ADDENDUM: THANK YOU VERY MUCH! FOUR PEOPLE ANSWERED ALMOST SIMULTANEOUSLY AND ALL FOUR GAVE ME A HELPFUL ANSWER. I WISH I COULD ACCEPT ALL FOUR!

4条回答
混吃等死
2楼-- · 2019-08-03 23:14

This will store the new value in url:

var url = $(this).find('a').attr('href') + '-chinese';

and this will redirect the user's browser:

window.location.href = $(this).find('a').attr('href') + '-chinese'
查看更多
smile是对你的礼貌
3楼-- · 2019-08-03 23:18
var url = $(this).find('a').attr('href') + "-chinese";
查看更多
唯我独甜
4楼-- · 2019-08-03 23:19
var $a = $(this).find('a');
var url = $a.attr('href');
$a.attr('href', url + '-chinese');
查看更多
beautiful°
5楼-- · 2019-08-03 23:30

You want to append the string "-chinese" to the retrieved URL? Try this:

var url = $(this).find('a').attr('href') + '-chinese';
查看更多
登录 后发表回答