admin 管理员组文章数量: 1086019
I have a string with words followed by a colon. I need to replace the colon words in that string with values from an object. I was able to extract out the colon words but not sure on the best way to replace it in the string.
This is what I have:
const string = 'This is :state :buttonName by :name';
const buttonName = 'button link';
const data = {
state: 'Alabama',
name: 'Arun'
}
const res = string.match(/:[a-zA-Z]+/g).map(i => i.replace(':', ''))
console.log(res)
// This is Alabama button link by Arun
I have a string with words followed by a colon. I need to replace the colon words in that string with values from an object. I was able to extract out the colon words but not sure on the best way to replace it in the string.
This is what I have:
const string = 'This is :state :buttonName by :name';
const buttonName = 'button link';
const data = {
state: 'Alabama',
name: 'Arun'
}
const res = string.match(/:[a-zA-Z]+/g).map(i => i.replace(':', ''))
console.log(res)
// This is Alabama button link by Arun
End result should be
This is Alabama button link by Arun
Please advice.
Share Improve this question asked Jun 1, 2021 at 17:00 arunmmanoharanarunmmanoharan 2,6753 gold badges37 silver badges74 bronze badges 3- 1 Does this answer your question? How to replace all occurrences of a string in JavaScript – Jeff B Commented Jun 1, 2021 at 17:02
-
us regex global flag
replace(/:/g, '')
– ShadowLp174 Commented Jun 1, 2021 at 17:06 -
1
Certainly it is not a duplicate of
Can ES6 template literals be substituted at runtime (or reused)?
as here, the problem is with matching specifically formatted tags (that start with:
and then only contain letters - not the case in that thread) and replacing them with items from a "dictionary". How to replace all occurrences of a string in JavaScript is not related at all. – Wiktor Stribiżew Commented Jun 2, 2021 at 8:27
4 Answers
Reset to default 7First of all, you need to move const buttonName = 'button link';
to the array.
You need to use String#replace
, but also you need to capture the part of the regex after :
and actually use the Group #1 value as key to get the right data
value.
Besides, you need to check if the extracted key is inside the dictionary to avoid issues.
You can use
const string = 'This is :state :buttonName by :name';
const data = {
buttonName: 'button link',
state: 'Alabama',
name: 'Arun'
}
const res = string.replace(/:([a-zA-Z]+)/g, (m, i) => i in data ? data[i] : m)
console.log(res)
You can split
the string and then call array map
to replace words and the join
to final string
const str= 'This is :state :buttonName by :name';
str.split(' ').map(a => {
if(a.startsWith(":"))
return data[a.replace(":","")];
return a;
}).join(' ');
If you've already stripped the ":" from the string you can just iterate your object keys and replace them with the respective values.
...
const res = string.match(/:[a-zA-Z]+/g).map(i => i.replace(':', ''))
for (const [key, value] of Object.entries(data)) {
res = res.replaceAll(key, value);
}
Wiktor's answer is good. But if it needs to replace the global variable as well, we can write the code as belows.
const res = string.replace(/:([a-zA-Z_]+)/g, (m, i) => data[i] ?? eval(i) ?? m);
console.log(res)
This code didn't do exception handling yet. It should be in consideration. So we can define a replacer function handling exception
const replacer = (m, i) => {
try {
return data[i] ?? eval(i);
} catch {
return m;
}
}
const res = string.replace(/:([a-zA-Z_]+)/g, replacer);
本文标签: javascriptReplace certain values in a string based on a mappingJSStack Overflow
版权声明:本文标题:javascript - Replace certain values in a string based on a mapping - JS - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://roclinux.cn/p/1744055966a2525853.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论