我有一個獲取字符串的函數,我在尋找一種方法來格式化第三個單詞(數字,我想用逗號格式化)。任何想法如何做到這一點? 應該是類似的東西:替換句子中的第n個詞
function formatNumber(txt){
return txt.replace(3rd-word, formatNumber(3rd-word));
}
我有一個獲取字符串的函數,我在尋找一種方法來格式化第三個單詞(數字,我想用逗號格式化)。任何想法如何做到這一點? 應該是類似的東西:替換句子中的第n個詞
function formatNumber(txt){
return txt.replace(3rd-word, formatNumber(3rd-word));
}
您可以通過拆分它,執行所指定的字指數更換得到句子的第n個字。
這裏是下面的代碼演示:DEMO
var sentence = "Total is 123456789!"
var formatNumber = function(value) {
return value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
var replaceWord = function(sentence, pos, formatterFunction) {
var matches = sentence.match(/(\b[^\s]+\b)/g);
if (pos < 0 && pos >= matches.length) {
throw "Index out of bounds: " + pos;
}
var match = matches[pos];
var bounded = new RegExp('\\b' + match + '\\b');
return sentence.replace(bounded, formatterFunction(match));
};
console.log(replaceWord(sentence, 2, formatNumber)); // Total is 123,456,789!
匹配包含數字的字,並且將其格式化:使用格式化功能,例如
txt = txt.replace(/\b(\d+)\b/g, format);
:
function format(s) {
var r = '';
while (s.length > 3) {
r = ',' + s.substr(s.length - 3) + r;
s = s.substr(0, s.length - 3);
}
return s + r;
}
這隻會匹配'-1.2345e9'中的'1',這可能不是OP在尋找「一個號碼。」 –
@MikeSamuel:這是可能的,但問題並不清楚。答案的第一句提到了這個限制。 – Guffa
將其分解爲若干部分。
這並不能解決您的問題。你仍然需要找到一種方式,你選擇格式化數字,但它解決了uppercasing第三個單詞的一個類似的問題:
var transformNth = function(n, fn) {
return function(arr) {
arr[n] = fn(arr[n]);
return arr;
}
};
var makeWords = function(sentence) {return sentence.split(" ");};
var upperCase = function(word) {return word.toUpperCase();}
var transformSentence = function(sentence) {
// index 2 is the third word
return transformNth(2, upperCase)(makeWords(sentence)).join(" ");
}
transformSentence("I have a function that get string");
//=> "I have A function that get string"
transformSentence("I'm looking for a way to format the 3rd word");
//=> "I'm looking FOR a way to format the 3rd word"
transformSentence("which is number");
//=> "which is NUMBER"
transformSentence("that i want to format it with comma");
//=> "that i WANT to format it with comma"
transformSentence("any idea how to do it?");
//=> "any idea HOW to do it?"
transformSentence("should be something like that");
//=> "should be SOMETHING like that"
它可能有問題,如果你的句子比一個空格一些更復雜的結構分離你想要維護的詞...
爲什麼你不只是匹配第一組數字? – epascarello
「單詞」是什麼意思?在許多語言中,單詞不是由空格分隔的,因此尋找單詞邊界[並非微不足道](http://en.wikipedia.org/wiki/Text_segmentation)。 –