Skip to content
Advertisement

Get the value of substring and then replace that with another string in js

I have a string

Date    Id    Number    Owner   GenderMaleFemale    Employment TypeExperiencedFresher   Issue TypeAutomation Code (script typos, File issues) Code (data model errors, utility errors)Platform Issues(db start up, network)Selectnull   

I want to replace GenderMaleFemale with Gender, Employment TypeExperiencedFresher with Employment Type and replace Issue TypeAutomation Code (script typos, File issues) Code (data model errors, utility errors)Platform Issues(db start up, network)Selectnull with Issue Type in the string itself.

The values of Issue Type are never constant. I want this change to happen dynamically. How can I achieve this?

EDIT: I tried doing

var string = "Date  Id    Number    Owner   GenderMaleFemale    Employment TypeExperiencedFresher   Issue TypeAutomation Code (script typos, File issues) Code (data model errors, utility errors)Platform Issues(db start up, network)Selectnull   "
string = string.replace("GenderMaleFemale", "Gender") 
console.log(string) // It replaces the GenderMaleFemale string as Gender. 
// But I don't know the value after Gender usually. Right now the options added are Male, Female if a new option gets added then I need to change the code. So I want replacement to be dynamic.
// I want to achieve something like
string = string.replace(/Gender/g, "Gender") // The output should be GenderMaleFemale word replaced as Gender.

Advertisement

Answer

Using regex is the right idea. By defining a regex which looks for the characters Gender, followed by all non-whitespace characters you can identify any form of GenderX until a whitespace is met.

string = string.replace(/(s)Gender[^s]+/, '$1Gender');

I also included a whitespace character in front of Gender that is preserved in the replacement ($1).

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement