2017-04-27 32 views
-1

請幫助解決我的問題。如何從文本中獲取字符串的部分並通過javascript格式化文本

我有一個完整的字符串:

var str = "I have 1000.00 USD montly to extract from 10000.00 USD. My account have 9000.00 USD." 

我要的是:

var str = "I have <mark>1000.00 USD</mark> montly to extract from <mark>10000.00 USD</mark>. My account have <mark>9000.00 USD</mark>." 

問題是金額和貨幣將每一個時代改變。我想把<mark>標籤放在金額和貨幣的周圍。請指導我解決它的方式?

謝謝。

+1

'12千毫升瓶的價格是$ 500'。預期的產出? – Tushar

+0

你如何生成字符串?在那裏包裝文字會容易得多。 –

回答

0

const regex = /(\d+(\.\d{1,2})? \w{1,5})/gm; 
 
const str = `I have 1000.00 USD montly to extract from 10000.00 USD. My account have 9000.00 USD.`; 
 
const subst = `<mark>$1</mark>`; 
 

 
// The substituted value will be contained in the result variable 
 
const result = str.replace(regex, subst); 
 

 
console.log('Result: ', result);

+0

'「我23年前出生,所以我23歲。 –

+0

有什麼不對? –

+0

''我出生了 23年以前所以我是 23年舊「'。 –

2

假設1000.00 USD模式 - digits, a dot, digits, a whitespace and the currency

var str = "I have 1000.00 USD montly to extract from 10000.00 USD. My account have 9000.00 USD.", 
 
    res = str.replace(/\d+\.\d+\s\w+/g, "<mark>"+ "$&" + "</mark>"); 
 
    
 
    console.log(res);

+0

''我體重15.5殺手,在1.5小時內見到我''。 –

+0

@ibrahimmahrir你的例子是一個總的科幻小說; d –

+0

爲什麼?因爲我不可能只稱重15.5個殺戮? :P –

相關問題