[英]Is there a better and faster way to replace digits in string by the text in Javascript?
我想有效地 (一個在字符串上運行,而不是更多)將字符串中的1,2,3的值替換為其文本表示形式st,1、2、3。 為此,在JS中最有效的方法是什么?
例:
輸入 : Old value '2', new value: '1', predicted value: '3'
輸出 : Old value 'two', new value: 'one', predicted value: 'three'
這是我想出的解決方案:
function formatActionInSysHistory(strValue) {
let dict = {
1: 'one',
2: 'two',
3: 'three'
}
foo = strValue.replace(/[123]/g, val => dict[val])
console.log(foo)
}
formatActionInSysHistory("Old value '2', new value: '1', predicted value: '3'")
您可以使用regular expression
。 下面是一個例子。
let str = "Old value '2', new value: '1', predicted value: '3'"; const mapObj = { 1:"one", 2:"two", 3:"three" }; const replaceAll = (str, mapObj) => { const re = new RegExp(Object.keys(mapObj).join("|"),"gi"); return str.replace(re, function(matched){ return mapObj[matched.toLowerCase()]; }); } console.log(replaceAll(str, mapObj));
這個怎么樣?
var demoStr = "Old v1alue '2', new value: '1', predicted value: '3'"
function convertStr(str){
console.time('convertStr')
let enNum = ['zero','one','two','three']
str = str.replace(/(\d)/g,(matched,p1)=>{
return p1 && enNum[p1]
})
console.timeEnd('convertStr')
return str
}
convertStr(demoStr)
如果需要,請回答我自己的問題:
function formatActionInSysHistory(strValue) {
let dict = {
1: 'one',
2: 'two',
3: 'three'
}
foo = strValue.replace(/[123]/g, val => dict[val])
console.log(foo)
}
formatActionInSysHistory("Old value '2', new value: '1', predicted value: '3'")
還有更多的例子在這里 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.