5

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.

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)
dmr
  • 21,811
  • 37
  • 100
  • 138
  • So should the edited "testingFooMiscText" end up as "testing" or as "FooMiscText"? – yoozer8 Aug 11 '11 at 20:43
  • @dmr To clarify, you would want `'testing'` from `myString`, correct? – Charmander Aug 11 '11 at 20:44
  • So, if 'Foo' is in the string, you want to truncate the string starting at Foo? Is that what you're asking? – FishBasketGordo Aug 11 '11 at 20:45
  • @Charmander is correct. I want to end up with `'testing'` – dmr Aug 11 '11 at 20:45
  • A super awesome tidbit for indexOf: Use ~ as invert: if(~index) str = str.substr(index) -awesome read: http://timmywillison.com/pres/operators/#bitwise-operators - check out preceding slides for more context. – David Hobs Sep 09 '12 at 05:17

7 Answers7

6
var index = str.indexOf(str1);
if(index != -1)
    str = str.substr(index) 
hungryMind
  • 6,931
  • 4
  • 29
  • 45
6

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;
    }
}
FishBasketGordo
  • 22,904
  • 4
  • 58
  • 91
2

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

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

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

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

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

yoozer8
  • 7,361
  • 7
  • 58
  • 93
2
myString.substring(0, myString.indexOf(mySub))
Charmander
  • 196
  • 1
  • 14
0
var newString = mystring.substring(mystring.indexOf(mySub));
Paul
  • 35,689
  • 11
  • 93
  • 122
0

This should do the trick.

var myString = 'testingFooMiscText'
myString.substring(myString.indexOf('Foo'))  //FooMiscText
myString.substring(myString.indexOf('Bar'))  //testingFooMiscText
Jeff
  • 13,943
  • 11
  • 55
  • 103
-2

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

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);
    } 
}
Brunner
  • 1,945
  • 23
  • 26