You can do exactly what you have :)
var string = "|0|0|0|0";
var newString = string.replace('|','');
alert(newString); // 0|0|0|0
You can see it working here, .replace() in javascript only replaces the first occurrence by default (without /g), so this works to your advantage :)
If you need to check if the first character is a pipe:
var string = "|0|0|0|0";
var newString = string.indexOf('|') == 0 ? string.substring(1) : string;
alert(newString); // 0|0|0|0βββββββββββββββββββββββββββββββββββββββββ
You can see the result here
Answer from Nick Craver on Stack OverflowHow to replace the first occurrence of a character with a string in JavaScript? - Stack Overflow
jquery - Why does javascript replace only first instance when using replace? - Stack Overflow
javascript - How to replace all BUT the first occurrence of a pattern in string - Stack Overflow
javascript - replace first occurrence of string after another string - Stack Overflow
You can do exactly what you have :)
var string = "|0|0|0|0";
var newString = string.replace('|','');
alert(newString); // 0|0|0|0
You can see it working here, .replace() in javascript only replaces the first occurrence by default (without /g), so this works to your advantage :)
If you need to check if the first character is a pipe:
var string = "|0|0|0|0";
var newString = string.indexOf('|') == 0 ? string.substring(1) : string;
alert(newString); // 0|0|0|0βββββββββββββββββββββββββββββββββββββββββ
You can see the result here
str.replace(/^\|/, "");
This will remove the first character if it's a |.
Put your replacements in a map, once a replacement is made, set map[x] to 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
repl = {...as before...}
result = subject.replace(/{(.+?)}/g, (_, x) => repl[x])
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. 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. A sequence which serves as a placeholder to be replaced should (or must) be different from a literal, e.g.:
var filename_format = "{L}_{N}_L_{D}";
You need to set the g flag to replace globally:
date.replace(new RegExp("/", "g"), '')
// or
date.replace(/\//g, '')
Otherwise only the first occurrence will be replaced.
Unlike the C#/.NET class library (and most other sensible languages), when you pass a String in as the string-to-match argument to the string.replace method, it doesn't do a string replace. It converts the string to a RegExp and does a regex substitution. As Gumbo explains, a regex substitution requires the gβlobal flag, which is not on by default, to replace all matches in one go.
If you want a real string-based replaceβββfor example because the match-string is dynamic and might contain characters that have a special meaning in regexenβββthe JavaScript idiom for that is:
var id= 'c_'+date.split('/').join('');
You can try a negative lookahead, avoiding the start of the string:
/(?!^)l/g
See if online: jsfiddle
There's no JS RegExp to replace everything-but-the-first-pattern-match. You can, however, implement this behaviour by passing a function as a second argument to the replace method.
var regexp = /(foo bar )(red)/g; //Example
var string = "somethingfoo bar red foo bar red red pink foo bar red red";
var first = true;
//The arguments of the function are similar to $0 $1 $2 $3 etc
var fn_replaceBy = function(match, group1, group2){ //group in accordance with RE
if (first) {
first = false;
return match;
}
// Else, deal with RegExp, for example:
return group1 + group2.toUpperCase();
}
string = string.replace(regexp, fn_replaceBy);
//equals string = "something foo bar red foo bar RED red pink foo bar RED red"
The function (fn_replaceBy) is executed for each match. At the first match, the function immediately returns with the matched string (nothing happens), and a flag is set.
Every other match will be replaced according to the logic as described in the function: Normally, you use $0 $1 $2, et cetera, to refer back to groups. In fn_replaceBy, the function arguments equal these: First argument = $0, second argument = $1, et cetera.
The matched substring will be replaced by the return value of function fn_replaceBy. Using a function as a second parameter for replace allows very powerful applcations, such as an intelligent HTML parser.
See also: MDN: String.replace > Specifying a function as a parameter
You don't need to add g modifier while replacing only the first occurance.
str.replace(/\b(here\b.*?)\bstring\b/, "$1anotherString");
DEMO
If you are looking for something which takes in a sentence and replaces the first occurrence of "string" after "here" (using the example in your case),
You should probably look at split() and see how to use it in a greedy way referring to something like this question. Now, use the second half of the split string
Then use replace() to find "string" and change it to "anotherString". By default this function is greedy so only your first occurrence will be replaced.
Concatenate the part before "here" in the original string, "here" and the new string for the second half of the original string and that will give you what you are looking for.
Working fiddle here.
inpStr = "this is a string test with a lot of string words here another string string there string here string."
firstHalf = inpStr.split(/here(.+)?/)[0]
secondHalf = inpStr.split(/here(.+)?/)[1]
secondHalf = secondHalf.replace("string","anotherString")
resStr = firstHalf+"here"+secondHalf
console.log(resStr)
Hope this helps.