taabma
taabma

Reputation: 67

simple if statement with if

I am trying to add a word into a string if it is not in there. And I converted the string into an array(an) like this and used push to add the new word but the new word is getting added (an.length - 1) times.

How can I fix this?

var ime = "open it now"
var an = ime.split(' ')
var ene = "itt"
for(var i = 0; i < ano.length; i++){

  if(an[i] != ene)

   an.push(ene) 

}
console.log(an) 

Upvotes: 1

Views: 80

Answers (5)

Prateek Jain
Prateek Jain

Reputation: 1552

it should work.

var ime = "open it now";
var ene = "itt";
var an = ime.split(' ')

if( an.indexOf(ene) == -1)
  ime += " "+ene;
console.log(ime);       

Upvotes: 0

Youness
Youness

Reputation: 1495

try this :

var ime = "open it now";
var ene = "itt";
if(ime.indexOf(ene) < 0)
    ime += " "+ene;
console.log(ime);

Upvotes: 0

Manwal
Manwal

Reputation: 23836

Try indexOf to check value present or not.

var ime = "open it now"
var an = ime.split(' ')
var ene = "itt";
if(an.indexOf(ene)==-1)
{
  an.push(ene);
}

DEMO

Upvotes: 0

adeneo
adeneo

Reputation: 318262

You should be using indexOf and string concantenation

ime = ime.indexOf( ene ) === -1 ? ime + ' ' + ene : ime

FIDDLE

Upvotes: 1

Christos
Christos

Reputation: 53958

You could use the method called indexOf for that you want.

For example:

var input = "you input string";
var word = "the word you are looking for";
// If the word you are looking for is not contained in you string,
// add it at the end of it.
if(input.indexOf(word)===-1)
{
    input = input + ' ' +word;
}

If you need more documenation about this method, indexOf, please have a look here.

Upvotes: 0

Related Questions