簡體   English   中英

獲取substring的值,然后用js中的另一個字符串替換

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

我有一個字符串

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   

我想用Gender替換GenderMaleFemale ,用Employment Type Employment TypeExperiencedFresher替換Issue TypeAutomation Code (script typos, File issues) Code (data model errors, utility errors)Platform Issues(db start up, network)Selectnull與字符串中的Issue Type本身。

問題類型的值從不恆定。 我希望這種變化動態發生。 我怎樣才能做到這一點?

編輯:我試着做

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.

使用正則表達式是正確的想法。 通過定義一個查找字符Gender的正則表達式,后跟所有非空白字符,您可以識別任何形式的GenderX ,直到遇到空白。

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

我還在Gender前面添加了一個空格字符,它保留在替換 ( $1 ) 中。

Replace Methid 將返回新字符串,因此您必須將其初始化為自身。

嘗試這個:-

var WholeString =  '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   ';

WholeString = WholeString.replace('GenderMaleFemale','Gender').replace('Employment TypeExperiencedFresher','Employment Type').replace('Issue TypeAutomation Code (script typos, File issues) Code (data model errors, utility errors)Platform Issues(db start up, network)Selectnull','Issue Type');

console.log(WholeString)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM