最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Replace last forward slash in string with other character - Stack Overflow

programmeradmin4浏览0评论

I'm trying to replace the last forward slash in a series of url strings, to exchange that forward slash for a number sign, like so -


to


Using JS with jQuery I've tried applying the replace function on each string but not sure as how to target just the last forward slash.

$('.submenu a').each(function() {
    var url = $(this).attr('href');
    url = url.replace(/\//g, '#');
    console.log(url);
    // replaces all
});

I'm trying to replace the last forward slash in a series of url strings, to exchange that forward slash for a number sign, like so -

http://example./about/our-pany

to

http://example./about#our-pany

Using JS with jQuery I've tried applying the replace function on each string but not sure as how to target just the last forward slash.

$('.submenu a').each(function() {
    var url = $(this).attr('href');
    url = url.replace(/\//g, '#');
    console.log(url);
    // replaces all
});
Share Improve this question asked Jan 28, 2014 at 12:06 Staffan EstbergStaffan Estberg 7,03517 gold badges75 silver badges108 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 8

Try this:

var str = "http://one/two/three/four";
console.log(str.replace(/\/(?=[^\/]*$)/, '#'));

That says: "replace the slash that is followed by either nothing or characters that do not include another slash, right to the end."

$('.submenu a').each(function() {
    var url = $(this).attr('href');
    var idx = url.lastIndexOf("/");
    url = url.substring(0, idx) + '#' + url.substring(idx+1);
    console.log(url);
});

You can try splitting Url based on /:

url = 'http://example./about/our-pany';
tokens = url.split('/');
expected_url = tokens.slice(0, tokens.length-1).join('/') + '#' + tokens[tokens.length-1];

console.log(expected_url);
# Prints 'http://example./about#our-pany'

A simple solution:

var str="http://example./about/our-pany";
var tmp=str.split("").reverse().join("");
tmp=tmp.replace("/","#");
str=tmp.split("").reverse().join("");

//output:

str = http://example./about#our-pany
发布评论

评论列表(0)

  1. 暂无评论