Gadde
Gadde

Reputation: 1471

Remove after a particular String

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

Answers (6)

Gadde
Gadde

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

techfoobar
techfoobar

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

Talha Akbar
Talha Akbar

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

NawaMan
NawaMan

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

Bartłomiej Mucha
Bartłomiej Mucha

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

Junnan Wang
Junnan Wang

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

Related Questions