Reputation: 23
If I have this string
"Something [10], Something else [10].\nBla bla bla [Not always a number].";
Considering that […]
identifies a special element that can be modified,
How would you write a function to have the following result?
var findReplaceElemByPosition = function(delimiters,position,new_value){
//find all the substrings delimited by the *delimimters*
//select only the one in a certain *position*
//replace the old value with the *new_value*
}
var myStrangeString = "Something[10], Something else [10].\nBla bla bla [Not always a number].";
myTransformedString = findReplaceElemByPosition("[]",0,20);
myTransformedString = findReplaceElemByPosition("[]",1,21);
myTransformedString = findReplaceElemByPosition("[]",2,"sometimes just a string");
// expected: myTransformedString = "Something[20], Something else [21].\nBla bla bla [sometimes just a string]."
I found a solution by adding spaces before and after delimiters and splitting the text in an array, but I wonder if there is a more elegant (and professional) solution.
Upvotes: 0
Views: 1073
Reputation: 6211
given an array of inputs like so:
const replacments = [
20,
21,
'some string'
]
you can easily replace all the string occurances by using the callback function of replace
method using regexp.
function run(string, replacements) {
const replaceBy = replacements.slice() // just to be safe
return string.replace(/\[[^\]]*\]/g, (original) => {
if (replaceBy.length) {
return `[${replaceBy.shift()}]`
}
return original
})
}
This function can be run as:
const string = 'Something[10], Something else [10].\nBla bla bla [Not always a number].'
const replacements = [20, 21, 'sometimes just a string']
run(string, replacements)
// returns 'Something[20], Something else [21].\nBla bla bla [sometimes just a string].'
It should now be a matter of juggling with the regex to also make the delimiter a parameter, for which you need to use new RegExp
, properly escape every special character and also inside the replacer function re-wrap it with the right delimiter.
Upvotes: 1