I am trying to create a function that builds a string made up of the characters of two given strings.
The function has 3 arguments:
searchString- a String that is scanned character by character to identify the position ofnewCharacteroriginalString- a string the same length as searchStringnewCharacter- a 1 character string.
The function should return a new string that contains newCharacter in the same positions as in searchString otherwise the characters at the corresponding positions of the originalString.
Example:
searchString = data,
originalString = bcde
newCharacter = a
The function would return "bada".
Cœur
39k25 gold badges207 silver badges282 bronze badges
asked Sep 18, 2011 at 7:43
Ross Cheeseright
1151 gold badge1 silver badge8 bronze badges
2 Answers 2
try this:
var rossFn = function (searchString, originalString, newCharacter) {
var initialValue = "";
for (var i = 0; i < searchString.length; i++) {
if (searchString.charAt(i) === newCharacter) {
initialValue += newCharacter;
} else {
initialValue += originalString.charAt(i);
}
}
return initialValue;
}
answered Sep 18, 2011 at 7:56
evan
4,3081 gold badge20 silver badges18 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
Ross Cheeseright
Thanks a lot for this. I'm sorry that it doesn't make much sense. I have elaborated a little on the initial question. You guys clearly have superior brains :)
Ross Cheeseright
Ah, thanks a lot! You're a genius. it works perfectly. Haha. I'm amazed that you were able to figure that out from my gibberish.
Another way to solve this:
function manipulateString(searchString, originalString, newCharacter)
{
//convert strings to array
searchString = searchString.split('');
originalString = originalString.split('');
//find indices in the search string where new character occurs
var matchingIndicesInSearchString = searchString.reduce(function(a, e, i) {
if (e === newCharacter)
a.push(i);
return a;
}, []);
matchingIndicesInSearchString.forEach(function (value, index, array)
{ //replace characters in the original string with the new character at the right indices
originalString.splice(value,1, newCharacter);
});
//convert array back to string
return originalString.toString().replace(/,/g,'');
}
It works. Please use like so:
var searchString = 'data',
originalString = 'bcde',
newCharacter = 'a';
manipulateString(searchString, originalString, newCharacter); //outputs 'bada'
Comments
lang-js
targetString? Another argument?