javascript 如果字符串中的子字符串,则从字符串的末尾将其删除

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7032555/
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-10-25 22:45:54  来源:igfitidea点击:

If substring in string, remove it through the end from string

javascriptreplace

提问by dmr

I'm trying to figure out how to do the following with javascript:
If a substring is in the string, remove from the beginning of the substring till the end of the string from the string.

我试图弄清楚如何使用 javascript 执行以下操作:
如果字符串中有子字符串,则从子字符串的开头到字符串的末尾删除。

For example (pseudocode):

例如(伪代码):

var mySub = 'Foo'
var myString = 'testingFooMiscText'
var myString2 = 'testingMisctext'

var myStringEdit = //myString - (Foo till end myString)
var myString2Edit = myString2 //(cause no Foo in it)

回答by hungryMind

var index = str.indexOf(str1);
if(index != -1)
    str = str.substr(index) 

回答by FishBasketGordo

If I understand what you're asking, you'll want to do this:

如果我明白你在问什么,你会想要这样做:

function replaceIfSubstring(original, substr) {
    var idx = original.indexOf(substr);
    if (idx != -1) {
        return original.substr(idx);
    } else {
        return original;
    }
}

回答by yoozer8

If you want "testingFooMiscText" to end up as "testing", use

如果您希望“testingFooMiscText”最终成为“testing”,请使用

word = word.substring(0, word.indexOf("Foo"));

If you want "testingFooMiscText" to end up as "FooMiscText", use

如果您希望“testingFooMiscText”最终成为“FooMiscText”,请使用

word = word.substring(word.indexOf("Foo"));

You may need a +/- 1 after the indexOf() to adjust the start/end of the string

您可能需要在 indexOf() 之后使用 +/- 1 来调整字符串的开始/结束

回答by Charmander

myString.substring(0, myString.indexOf(mySub))

回答by Jeff

This should do the trick.

这应该可以解决问题。

var myString = 'testingFooMiscText'
myString.substring(myString.indexOf('Foo'))  //FooMiscText
myString.substring(myString.indexOf('Bar'))  //testingFooMiscText

回答by Paul

var newString = mystring.substring(mystring.indexOf(mySub));

回答by Arun Sule

I used following code to eliminate fakefile from file Name and it worked.

我使用以下代码从文件名中消除了 fakefile 并且它起作用了。

function confsel()
{
    val = document.frm1.fileA.value;
    value of val comes like C:\fakepath\fileName
    var n = val.includes("fakepath");
    if(n)
    {
        val=val.substring(12);
    } 
}