Joe
Joe

Reputation: 4234

Replace last part of string, javascript

const str = ".1.2.1"

const str2 = ".1";

const func = (str, str2) => {
 ...
}

expected output = ".1.2"

Another example:

str = "CABC"
str2 = "C"
Expected output "CAB"

So the last part of the string that matches the end of the string should be removed.

Can this be done with some neat build-in-function in javascript?

Update

Updated string example. Simple replace does not work.

Upvotes: 0

Views: 1193

Answers (5)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521457

Just try replacing \.\d+$ with empty string, using a regex replacement:

var input = "1.2.1";
input = input.replace(/\.\d+$/, "");
console.log(input);

Edit:

Assuming the final portion of the input to be removed is actually contained in a string variable, then we might be forced to use RegExp and manually build the pattern:

var str = "CABC"
var str2 = "C"
var re = new RegExp(str2 + "$");
str = str.replace(re, "");
console.log(str);

Upvotes: 6

Cid
Cid

Reputation: 15247

You can check the position of the string to find using lastIndexOf and if it is at its supposed position, then just slice

function removeLastPart(str, str2)
{
  result = str;
  
  let lastIndex = str.lastIndexOf(str2);
  if (lastIndex == (str.length - str2.length))
  {
    result = str.slice(0, lastIndex)
  }
  return result;
}

console.log(removeLastPart(".1.2.1", ".1"));
console.log(removeLastPart("CABC", "C"));
console.log(removeLastPart(" ispum lorem ispum ipsum", " ipsum"));

// should not be changed
console.log(removeLastPart("hello world", "hello"));
console.log(removeLastPart("rofllollmao", "lol"));

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386654

You could create a regular expression from the string and preserve the dot by escaping it and use the end marker of the string to replace only the last occurence.

const
    replace = (string, pattern) => string.replace(new RegExp(pattern.replace(/\./g, '\\\$&') + '$'), '')

console.log(replace(".1.2.1", ".1"));
console.log(replace("CABC", "C"));

Upvotes: 2

adiga
adiga

Reputation: 35222

You could create a dynamic regex using RegExp. The $ appended will replace str2 from str ONLY if it is at the end of the string

const replaceEnd = (str, str2) => {
  const regex = new RegExp(str2 + "$");
  return str.replace(regex, '')
}

console.log(replaceEnd('.1.2.1', '.1'))
console.log(replaceEnd('CABC', 'C'))

Upvotes: 0

Radonirina Maminiaina
Radonirina Maminiaina

Reputation: 7004

You can use String.prototype.slice

const str = "1.2.1"

const str2 = ".1";

const func = (str) => {
 return str.slice(0, str.lastIndexOf("."));
}

console.log(func(str));

Upvotes: 0

Related Questions