[英]How to replace the first occurrence of a character with a string in JavaScript?
I have a string which contains characters that should be replaced once (at first appearance). 我有一个字符串,其中包含应该替换一次的字符(首次出现时)。
These characters are: 这些字符是:
Example input: 输入示例:
L_N_L_D
Desired result (note that only the first L
is replaced): 期望的结果 (注意只替换第一个
L
):
Math_Ex01_L_2018-10-05
My current code (simplified for the example): 我当前的代码 (示例简化):
let res = file_string.replace(/L|N|D/, x => {
switch (x) {
case 'L': return lecture;
case 'N': return name;
case 'D': return date;
default: return x;
}
});
What I get is this: 我得到的是这个:
Math_L_N_D
If I change the regex to /L|N|D/g
the second L
will also be replaced which is not what I want. 如果我将正则表达式更改为
/L|N|D/g
则第二个L
也将被替换,这不是我想要的。
How could this be implemented? 怎么能实现呢?
Answering your general question "replace only the first occurrence of a character", you could do it like this: 回答你的一般问题“只替换第一次出现的角色”,你可以这样做:
var lecture = "Math"; var name = "Ex01"; var date = "2018-10-05"; var found = {}; var file_string = "L_N_L_D"; var filename_result = file_string.split("").map(function (character) { if (!found[character]) { found[character] = true; switch (character) { case "L": return lecture; case "N": return name; case "D": return date; } } return character; }).join(""); console.log(filename_result);
You should probably explain where that odd format of the file_string
comes from. 您应该解释
file_string
奇怪格式来自file_string
。 Are there other similar use cases? 还有其他类似的用例吗? Or is this just about this specific example?
或者这仅仅是这个具体的例子? Understanding the original requirements would help a lot.
了解原始要求会有很大帮助。
If the file_string
is supposed to be a configurable format string, then it should be improved. 如果
file_string
应该是可配置的格式字符串,那么应该对其进行改进。 A sequence which serves as a placeholder to be replaced should (or must ) be different from a literal, eg: 作为要替换的占位符的序列应该(或必须 )与文字不同,例如:
var filename_format = "{L}_{N}_L_{D}";
Put your replacements in a map, once a replacement is made, set map[x]
to x
: 将替换放在地图中,一旦替换,将
map[x]
设置为x
:
let lecture = "Math"; let name = "Ex01"; let date = "2018-10-05"; let repl = { 'L': lecture, 'N': name, 'D': date }; let file_string = "L_N_L_D" let result = file_string.replace(/[LND]/g, x => { let r = repl[x]; repl[x] = x; return r; }); console.log(result)
Apart from solving the problem at hand, this also greatly simplifies your replacement function (think adding new placeholders, for example). 除了解决手头的问题,这也大大简化了您的替换功能(例如,想想添加新的占位符)。
That being said, a real solution to your problem would be to follow the @marsze's advice and use unambiguous placeholders, like {...}
, in which case the whole enterprise becomes simply 话虽这么说,你的问题的一个真正的解决方案是遵循@ marsze的建议并使用明确的占位符,如
{...}
,在这种情况下,整个企业变得简单
repl = {...as before...}
result = subject.replace(/{(.+?)}/g, (_, x) => repl[x])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.