i want to replace string from
"I am master at string" to "I zm master zt string"
I don not want to replace all character ‘a’ or only first character i want to replace only those character which starts with ‘a’ if word have ‘a’ in between it should not replaced
in string there is method called replace() but with replace we can only change first occurance or using with regx g we can replace all the character but i want to replace all ‘a’ character with ‘z’ , only if ‘a’ is at first position in word. how can do with javascript
3
Answers
You can use a combination of the
split()
method to break the string into words, and then iterate through the words to check if the first character is ‘a’. If it is, replace the ‘a’ with ‘z’. Finally, use thejoin()
method to reassemble the string.edit:
as @evolutionxbox points out, you can simply use the following regular expression:
You can preserve case if you transform the matched letter to a char code, add 25, and convert back into a letter.
Note: The
b
(word boundary) before the target letter means start of word, and theig
flags toggle case-insensitive and global replace repectively.Here is a functional example:
Approach without regex. You can use
.split
got get an array of words. Use map with a condition (ternary syntax): if a word starts with "a", "z" is added as the first letter using a string literal and the the rest of the word usingsubstring
. Otherwise the word is unchanged. At the end, array is converted to string withjoin
.