简体   繁体   English

字符串将url替换为javascript中相同url的一部分

[英]String replace a url with part of the same url in javascript

I have string that contains a random url: 我有一个包含随机网址的字符串:

http://google.com/vocab/prefix#Billy

That needs to be transformed so that everything up to, and including the first # is replaced with the value between the last / and the first # followed by a : . 需要进行改造,使一切直到并且包括第一#替换为最后的值/和第一#后跟一个:

The result would be: 结果将是:

prefix:Billy

More examples: 更多示例:

http://some.url/a/path#elephant --> path:elephant
http://random.com/cool/black/beans/thing#Bob --> thing:bob

I understand how to capture the prefix part /([^\\/]+(?=#))/ , but I'm struggling to do a string replace because I can't figure out how to capture the part I need to replace. 我了解如何捕获前缀部分/([^\\/]+(?=#))/ ,但由于无法弄清楚如何捕获需要替换的部分,我一直在努力进行字符串替换。

myString.replace(/([^\/]+(?=#))/, '$1:')

I would prefer to use string.replace with regex if at all possible 我更愿意在正则表达式中使用string.replace

When using replace method you need to match all the patterns you want to replace instead of just the part you need to keep; 使用replace方法时,您需要匹配所有要替换的模式,而不仅仅是需要保留的部分; Here are two options: 这里有两个选择:

 let s = 'http://google.com/vocab/prefix#Billy' // using greedy regex console.log(s.replace(/.*\\/([^#]+)#/, '$1:')) // adapted from OP's attempt console.log(s.replace(/.*?([^\\/]+?)#/, '$1:')) 

Note .* part to match the substring you want to discard, () to capture the pattern you want to keep, then reformat the output. 注意.*部分与要舍弃的子字符串匹配, ()捕获要保留的模式,然后重新格式化输出。

Try this code: 试试这个代码:

var myString = "http://google.com/vocab/prefix#Billy";
var hashIndex = myString.indexOf("#"); // find where the "#" is

for(var i = hashIndex; i > 0; i--) { // loop from "#" index *back* to closest "/" symbol
  if(myString[i] == "/") break; // break loop when "/" is found
}

myString = myString.replace("#", ":"); // replace "#" with ":" as in your example

console.log(myString.substring(i, hashIndex); // output 

Shortened: 缩短:

var myString = "http://google.com/vocab/prefix#Billy".replace("#",":");
for(var i = myString.indexOf(":"); i > 0; i--) { if(myString[i] == "/") break; }
console.log(myString.substring(i, myString.indexOf(":");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM