uber
uber

Reputation: 5073

How to delete the last word of a string if it matches a certain word?

"Restaurant Chile - Santiago de Chile, 123904, Chile"

The word Chile appears many times, but I only want to remove the last one IF it is "Chile". If the string was

"Restaurant Chile - Santiago de Chile, 123904, Canada"

this would not delete any word.

Upvotes: 1

Views: 57

Answers (5)

zcoop98
zcoop98

Reputation: 3089

Another way to do this is using lastIndexOf() and slice():

const chileAddr = "Restaurant Chile - Santiago de Chile, 123904, Chile";
const canadaAddr = "Restaurant Chile - Santiago de Chile, 123904, Canada";

function removeIfEnd(searchTerm, str) {
  return (str.lastIndexOf(searchTerm) == (str.length - searchTerm.length))
    ? str.slice(0, -(searchTerm.length + 2)) // +2 to account for comma
    : str;
}

console.log(removeIfEnd('Chile', chileAddr));
console.log(removeIfEnd('Chile', canadaAddr));

Upvotes: 0

sonEtLumiere
sonEtLumiere

Reputation: 4562

Try this

let str = "Restaurant Chile - Santiago de Chile, 123904, Chile";
let splited = str.split(' ');

if(splited[splited.length - 1] == 'Chile'){
    splited.pop()
}

let result = splited.join(' ');
console.log(result);

Upvotes: 0

gillall
gillall

Reputation: 111

You will probably want to remove the comma

Not cool, not fancy, but works in this case.

var str = "Restaurant Chile - Santiago de Chile, 123904, Chile";

str = str.replace(", Chile"," ")

Upvotes: 0

antonku
antonku

Reputation: 7665

You can use a regular expression:

const result = "Restaurant Chile - Santiago de Chile, 123904, Chile".replace(/,\sChile$/, '')
console.log(result)

Upvotes: 3

ccStars
ccStars

Reputation: 815

var text = "Restaurant Chile - Santiago de Chile, 123904, Canada";
var wordToCheck = "Chile";

if(text.endsWith(wordToCheck)
{
  text = text.substr(text.lastIndexOf(wordToCheck),wordToCheck.length);
}

Upvotes: 0

Related Questions