Javascript 如何从给定的模式开始删除字符串的结尾?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10942790/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 03:41:48  来源:igfitidea点击:

How to remove the end of a string, starting from a given pattern?

javascript

提问by user765368

Let's say I have a string like this:

假设我有一个这样的字符串:

var str = "/abcd/efgh/ijkl/xxx-1/xxx-2";

How do I, using Javascript and/or jQuery, remove the part of strstarting with xxx, till the end of str?

我如何使用 Javascript 和/或 jQuery 删除从 ,str开始xxx到 结束的部分str

回答by Will

str.substring( 0, str.indexOf( "xxx" ) );

回答by haylem

Just:

只是:

s.substring(0, s.indexOf("xxx"))

A safer version handling invalid input and lack of matching patterns would be:

处理无效输入和缺少匹配模式的更安全版本是:

function trump(str, pattern) {
  var trumped = "";  // default return for invalid string and pattern

  if (str && str.length) {
    trumped = str;
    if (pattern && pattern.length) {
      var idx = str.indexOf(pattern);

      if (idx != -1) {
        trumped = str.substring(0, idx);
      }
    }
  }
  return (trumped);
}

which you'd call with:

你会打电话给:

var s = trump("/abcd/efgh/ijkl/xxx-1/xxx-2", "xxx");

回答by u283863

Try this:

尝试这个:

str.substring(0, str.indexOf("xxx"));

indexOfwill find the position of xxx, and substringwill cut out the piece you want.

indexOf会找到 的位置xxx,然后substring剪下你想要的部分。

回答by Hemeligur

Try using string.slice(start, end):

尝试使用string.slice(start, end)

If you know the exact number of characters you want to remove, from your example:

如果您知道要删除的确切字符数,请从示例中:

var str = "/abcd/efgh/ijkl/xxx-1/xxx-2";
new_str = str.slice(0, -11);

This would result in str_new == '/abcd/efgh/ijkl/'

这会导致 str_new == '/abcd/efgh/ijkl/'

Why this is useful:If the 'xxx'refers to any string (as the OP said), i.e: 'abc', '1k3', etc, andyou do not know beforehand what they could be (i.e: Not constant), the accepted answers, as well as most of the others will not work.

为什么这很有用:如果'xxx'指的是任何字符串(如 OP 所说),即:'abc'、'1k3' 等,并且您事先不知道它们可能是什么(即:不是常量),则接受的答案,以及其他大多数将不起作用。

回答by saluce

This will take everything from the start of the string to the beginning of xxx.

这将从字符串的开头到xxx.

str.substring(0,str.indexOf("xxx"));