我有一个获取字符串的函数,我正在寻找一种格式化第三个单词的方法(这是数字,我想用逗号格式化它)。任何想法怎么做? 应该是这样的:
function formatNumber(txt){
return txt.replace(3rd-word, formatNumber(3rd-word));
}
答案 0 :(得分:0)
你可以通过将它分开并在指定的单词索引上执行替换来从句子中获取第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!
答案 1 :(得分:0)
匹配任何由数字组成的单词,并对其进行格式化:
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;
}
答案 2 :(得分:0)
将其分解为部分。
这不能解决您的问题。您仍然需要找到一种方法来根据您的选择格式化数字,但它解决了类似的第三个词大写的问题:
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"
如果你的句子的结构比你想要维护的单个空格分隔更复杂,那么可能会有问题......