Reputation: 1471
I have some text content
atxtCtnt = "Helow Hay How Are You"
if Hay exists I need to remove Hay How Are You
I did it like this:
var atxtCtnt = "Helow Hay How Are You",
txt = atxtCtnt.substring(atxtCtnt.indexOf("Hay"));
atxtCtnt = atxtCtnt.replace(txt , "");
alert(atxtCtnt );
Please help me in better way without RegExp
Upvotes: 1
Views: 750
Reputation: 1471
this is what i did
var atxtCtnt = "Helow Hay How Are You",
txt = atxtCtnt.substring(0, atxtCtnt.indexOf("Hay"));
alert(txt );
thank u for your answers :)
Upvotes: 2
Reputation: 66663
This should work:
atxtCtnt = atxtCtnt.substring(0, atxtCtnt.indexOf("Hay"));
Edit: To account for if Hay
isn't there:
atxtCtnt = atxtCtnt.substring(0, atxtCtnt.indexOf("Hay") === -1 ? atxtCtnt.length : atxtCtnt.indexOf("Hay"));
Upvotes: 1
Reputation: 10030
var word = "Hay";
var a = "Helow Hay How Are You";
var b = a.split(word); // now you have two parts b[0] = Helow and b[1] = How Are You
document.body.innerHTML=b[0];
Upvotes: 1
Reputation: 25687
You need the sub string from 0 to the index. But only if the index is more than 0 (The term "Hay" exists in the text). Like this
var atxtCtnt = "Helow Hay How Are You";
var index = atxtCtnt.indexOf("Hay");
var newText = (index < 0) ? atxtCtnt : atxtCtnt.substring(0, index);
alert(newText);
Upvotes: 3
Reputation: 2782
I'm not sure if this is better solution than this with substrings, but you can also try this:
atxtCtnt.split('Hay')[0]
You can remove whitespace at the end of "Helow " like this:
atxtCtnt.split('Hay')[0].trim()
Upvotes: 1
Reputation: 657
If you don't want to use Regex... I think this will make your code a little bit shorter
a = atxtCtnt.indexOf('Hay');
atxtCtnt = a >=0?atxtCtnt.substring(0,a):atxtCtnt;
Upvotes: 3