如何删除字符串的一部分而不删除另一处的同一组字符?
How can I delete one part of the string without deleting the same set of characters in another place?
我正在尝试清理字符串 (URL)。每次它包含 ipfs://ipfs/
时,我都需要将其替换为单个 ipfs/
。
完整的字符串是 ipfs://ipfs/QmR6xjBCn
但应该是 ipfs://QmR6xjBCn
在某些情况下,我得到的字符串已经干净了,在其他情况下,我没有。
我已经使用 include 来检测字符串是否包含 ipfs://ipfs
,然后将其替换为我需要的内容:ipfs://
if (fixedURL.includes('ipfs://ipfs')) {
fixedURL2 = fixedURL.replace('ipfs://ipfs','ipfs://')
obj.imageUrl = fixedURL2;
} else {
obj.imageUrl = fixedURL;
}
使用 replace() 函数。如果文本不在字符串中,则它不会替换任何内容。所以它只有在双 ipfs 的情况下才有效。
let str;
// example one
str = "ipfs://ipfs/QmR6xjBCn";
str = str.replace("ipfs://ipfs/","ipfs://");
console.log(str);
// example two, same code different url
str = "ipfs://SomethingRandom";
str = str.replace("ipfs://ipfs/","ipfs://");
console.log(str);
我正在尝试清理字符串 (URL)。每次它包含 ipfs://ipfs/
时,我都需要将其替换为单个 ipfs/
。
完整的字符串是 ipfs://ipfs/QmR6xjBCn
但应该是 ipfs://QmR6xjBCn
在某些情况下,我得到的字符串已经干净了,在其他情况下,我没有。
我已经使用 include 来检测字符串是否包含 ipfs://ipfs
,然后将其替换为我需要的内容:ipfs://
if (fixedURL.includes('ipfs://ipfs')) {
fixedURL2 = fixedURL.replace('ipfs://ipfs','ipfs://')
obj.imageUrl = fixedURL2;
} else {
obj.imageUrl = fixedURL;
}
使用 replace() 函数。如果文本不在字符串中,则它不会替换任何内容。所以它只有在双 ipfs 的情况下才有效。
let str;
// example one
str = "ipfs://ipfs/QmR6xjBCn";
str = str.replace("ipfs://ipfs/","ipfs://");
console.log(str);
// example two, same code different url
str = "ipfs://SomethingRandom";
str = str.replace("ipfs://ipfs/","ipfs://");
console.log(str);