gpt4 book ai didi

javascript - 在这种情况下如何替换字符串并获得我需要的内容?

转载 作者:行者123 更新时间:2023-12-02 14:37:04 25 4
gpt4 key购买 nike

我正在尝试用两组模式替换字符串。例如,

var pattern1 = '12345abcde/';  -> this is dynamic.
var myString = '12345abcde/hd123/godaddy_item'

我的最终目标是获取两个斜杠之间的值,即hd123

我有

var stringIneed = myString.replace(pattern1, '').replace('godaddy_item','');

上面的代码可以工作,但我认为还有更优雅的解决方案。谁能帮我解决这个问题吗?非常感谢!

更新: 更清楚地说,该模式是针对每个环境字符串的。例如,pattern1 可能类似于:

https://myproject-development/item on development environment.

https://myproject/item on Production

myString 通常可能类似于

https://myproject/item/hd123/godaddy_item

https://myproject-development/item/hd123/godaddy_item

就我而言,我需要获取“hd123”。

最佳答案

我强烈建议不要为此使用正则表达式,特别是当简单的 StringArray 方法就足够了并且更容易理解时,例如:

// your question shows you can anticipate the sections you
// don't require, so put both/all of those portions into an
// array:
var unwanted = ['12345abcde', 'godaddy_item'],

// the string you wish to find the segment from:
myString = '12345abcde/hd123/godaddy_item',

// splitting the String into an array by splitting on the '/'
// characters, filtering that array using an arrow function
// in which the section is the current array-element of the
// array over which we're iterating; and here we keep those
// sections which are not found in the unwanted Array (the index
// an element not found in an Array is returned as -1):
desired = myString.split('/').filter(section => unwanted.indexOf(section) === -1);

console.log(desired); // ["hd123"]

对于不支持 ES6 的浏览器,避免使用箭头函数(并删除了代码注释):

var unwanted = ['12345abcde', 'godaddy_item'],
myString = '12345abcde/hd123/godaddy_item',
desired = myString.split('/').filter(function (section) {
return unwanted.indexOf(section) === -1;
});

console.log(desired); // ["hd123"]

或者:

// the string to start with and filter:
var myString = '12345abcde/hd123/godaddy_item',

// splitting the string by the '/' characters and keeping those whose
// index is greater than 0 (so 'not the first') and also less than the
// length of the array-1 (since JS arrays are zero-indexed while length
// is 1-based):
wanted = myString.split('/').filter((section, index, array) => index > 0 && index < array.length - 1);

console.log(wanted); // ["hd123"]

JS Fiddle demo

但是,如果要找到的必需字符串始终是所提供字符串的倒数第二部分,那么我们可以使用 Array.prototype.filter() 只返回该部分:

var myString = '12345abcde/hd123/godaddy_item',
wanted = myString.split('/').filter((section, index, array) => index === array.length - 2);

console.log(wanted); // ["hd123"]

JS Fiddle demo .

引用文献:

关于javascript - 在这种情况下如何替换字符串并获得我需要的内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37365905/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com