在这种情况下如何替换字符串并获得我需要的东西?

时间:2016-05-21 17:15:17

标签: javascript regex

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

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'就我而言。

5 个答案:

答案 0 :(得分:1)

您可以使用

.*\/([^\/]+)\/.*$

<强> Regex Demo

JS Demo

&#13;
&#13;
var re = /.*\/([^\/]+)\/.*$/g;
var str = '12345abcde/hd123/godaddy_item';

while ((m = re.exec(str)) !== null) {
    document.writeln("<pre>" + m[1] + "</br>" + "</pre>");
}
&#13;
&#13;
&#13;

答案 1 :(得分:1)

我强烈建议不要使用正则表达式,特别是当简单的StringArray方法很容易理解时,例如:

&#13;
&#13;
// 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"]
&#13;
&#13;
&#13;

避免箭头功能,适用于不支持ES6的浏览器(并删除了代码注释):

&#13;
&#13;
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"]
&#13;
&#13;
&#13;

或者:

&#13;
&#13;
// 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"]
&#13;
&#13;
&#13;

JS Fiddle demo

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

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

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

JS Fiddle demo

参考文献:

答案 2 :(得分:0)

您可以轻松地执行以下操作: myString.split('/').slice(-2)[0]

这将以简单的方式直接返回项目。

var myString = 'https://myproject/item/hd123/godaddy_item';
console.log(myString.split('/').slice(-2)[0]); // hd123
myString = 'https://myproject-development/item/hd123/godaddy_item';
console.log(myString.split('/').slice(-2)[0]); // hd123

答案 3 :(得分:0)

要说大卫的答案“足够容易并且更容易理解”是一个观点问题 - 这个正则表达式选项(包括从变量构建表达式)真的不会简单得多:

var pathPrefix = '12345abcde/'; //dynamic
var pathToTest = '12345abcde/hd123/godaddy_item';
var pattern = new RegExp(pathPrefix + '(.*?)\/')
var match = pattern.exec(pathToTest);
var result = (match != null && match[1] != null ? '[' + match[1] + ']' : 'no match was found.'); //[hd123]

答案 4 :(得分:0)

尝试使用match(),如下所示:

var re = /\/(.*)\//;
var str = '12345abcde/hd123/godaddy_item';
var result = str.match(re);
alert(result[1]);