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)
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)
Share
Improve this question
asked Aug 11, 2011 at 20:41
dmrdmr
22.3k37 gold badges104 silver badges139 bronze badges
5
|
7 Answers
Reset to default 6var index = str.indexOf(str1);
if(index != -1)
str = str.substr(index)
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;
}
}
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
myString.substring(0, myString.indexOf(mySub))
var newString = mystring.substring(mystring.indexOf(mySub));
This should do the trick.
var myString = 'testingFooMiscText'
myString.substring(myString.indexOf('Foo')) //FooMiscText
myString.substring(myString.indexOf('Bar')) //testingFooMiscText
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);
}
}
'testing'
frommyString
, correct? – Charmander Commented Aug 11, 2011 at 20:44'testing'
– dmr Commented Aug 11, 2011 at 20:45