最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

JavaScript string manipulation: remove prefix, suffix and lowercase first (in single line without assignments), possible? - Stac

programmeradmin14浏览0评论

Hope that this will not be closed, I can't find any suitable questions.

  1. Prefix is a variable
  2. Suffix is always the word Value
  3. Resulting value should have the first letter lowercase

Code so far, missing the lowercase for the first letter:

// Input: { toastDurationValue: 3000, toastPositionValue: 'bottom' }
// Wanted: { duration: 3000, position: 'bottom' }

const options = Object.keys(element.dataset)
  .filter(k => k.startsWith(prefix))
  .reduce((prev, curr) => ({
    ...prev,
    [curr.slice(prefix.length).replace(/(Value)$/, '')]: element.dataset[curr]
  }), {});

Hope that this will not be closed, I can't find any suitable questions.

  1. Prefix is a variable
  2. Suffix is always the word Value
  3. Resulting value should have the first letter lowercase

Code so far, missing the lowercase for the first letter:

// Input: { toastDurationValue: 3000, toastPositionValue: 'bottom' }
// Wanted: { duration: 3000, position: 'bottom' }

const options = Object.keys(element.dataset)
  .filter(k => k.startsWith(prefix))
  .reduce((prev, curr) => ({
    ...prev,
    [curr.slice(prefix.length).replace(/(Value)$/, '')]: element.dataset[curr]
  }), {});
Share Improve this question asked May 12, 2022 at 10:06 gremogremo 48.5k80 gold badges271 silver badges447 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 4

Just add

.toLowerCase()

after

.replace(/(Value)$/, '')

Here:

// Input: { toastDurationValue: 3000, toastPositionValue: 'bottom' }
const options = Object.keys(element.dataset)
  .filter(k => k.startsWith(prefix))
  .reduce((prev, curr) => ({
    ...prev,
    [curr.slice(prefix.length).replace(/(Value)$/, '').toLowerCase()]: element.dataset[curr]
  }), {});
console.log(options);

Output:

{ duration: 3000, position: 'bottom' }

This can be done in one statement, in an elaborate (difficult to read) way using slice(), replace() and toUpperCase(). The original string stays as it is:

let str = 'hellorandomWORDValue';
const prefix = 'hello';

const str2 = str.replace(prefix, "").slice(0,-5)[0].toUpperCase() + str.replace(prefix, "").slice(0,-5).slice(1)

console.log(str);
console.log(str2);

slice(0,5) -> removes the last 5 letter, so basically removes Value suffix.

replace(prefix,"") -> replaces first instances of the variable string prefix. So basically removes the prefix.

[0].toUpperCase() -> takes out the first character and makes it uppercase.

.slice(1) -> takes out rest of the string (from 1st index). Basically, rest of the string after first character.

const options = Object.keys(element.dataset)
  .filter(k => k.startsWith(prefix))
  .reduce((prev, curr) => ({
    ...prev,
    [curr.replace(prefix, "").slice(0,-5)[0].toUpperCase() + curr.replace(prefix, "").slice(0,-5).slice(1)]: element.dataset[curr]
  }), {});

May below snippet can contribute to your solution.

const obj = { toastDurationValue: 3000, toastPositionValue: 'bottom' }
const prefix = 'toast';

Object.keys(obj).forEach(key => {
    obj[key] = obj[key.substring(0, key.lastIndexOf('Value')).replace(prefix, '').toLowerCase()] = obj[key];
    delete obj[key];
})

console.log(obj);

For some reason mapping entries rather than reducing the object feels a tiny bit better to me:

const simplify_key = (key, prefix_length) =>
  key[prefix_length].toLowerCase() + key.substring(prefix_length + 1, key.length - 5);

const extract_options = (dataset, prefix = 'toast') =>
  Object.fromEntries(
    Object.entries(dataset)
      .filter(([key]) => key.startsWith(prefix))
      .map(([key, val]) => [simplify_key(key, prefix.length), val])
  );

console.log(extract_options({
  toastDurationValue: 3000,
  toastPositionValue: 'bottom',
  toastMoreTermsValue: 'thing',
  otherDataItem: 'wibble'
}));

HI

in case of trimming prefix and postfix you can use following replace with regex function

.replace(/(^suffix|postfix$)/g, "replace")

replace suffix with your starting string and postfix with corresponding too.

thanks.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论