Home > Enterprise >  remove suffix character in array in javaScript
remove suffix character in array in javaScript

Time:11-28

How can I remove some specific character inside an Array? for example;

var wording = ["She", "gives","me", "called", "friend"];
var suffix = ["s", "ed", "ing"];   
function p {
    return wording.substring(wording.substring(wording) - 1, wording.length - 1))
}
var text = wording.map(p);
console.log(text);
  • I want to remove 's' in the word 'gives' but I don't want to remove 'S' in 'She'.
  • I also want to remove an 'ed' in a word 'called' too.

CodePudding user response:

If one of the words being iterated over endsWith one of the strings, you can slice out the length of the found suffix.

var wording = ["She", "gives","me", "called", "friend"];
var suffix = ["s", "ed", "ing"];
const p = word => {
  const foundSuffix = suffix.find(str => word.endsWith(str));
  return !foundSuffix ? word : word.slice(0, -foundSuffix.length);
}
var text = wording.map(p);
console.log(text);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Another approach, using a regular expression:

const wording = ["She", "gives","me", "called", "friend"];
const suffix = ["s", "ed", "ing"];
const pattern = new RegExp(suffix.join('|')  '$');
const p = word => word.replace(pattern, '');
console.log(wording.map(p));
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

METHOD 1

var wording = ["She", "gives","me", "called", "friend"];
var suffix = ["s", "ed", "ing"];   
function p(w) {
    var ret = w;
    suffix.forEach(s => {
        if( w.endsWith(s) ) {
            ret = ret.slice(0,w.length - s.length);
        }
    })
    return ret
}
var text = wording.map(p);
console.log(text);
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

METHOD 2

var wording = ["She", "gives","me", "called", "friend"];
var suffix = ["s", "ed", "ing"];   
var text = wording
//check if any of the words end with any of the suffices min 0, max 1
.map(w => [w,suffix.filter(s => w.endsWith(s))])
//use the returned array to remove suffix, if found
.map(([w,s]) => s.length ? w.slice(0,w.length - s[0].length) : w);
console.log(text);
<iframe name="sif4" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related