2014-04-09 79 views
0

我有一个获取字符串的函数,我在寻找一种方法来格式化第三个单词(数字,我想用逗号格式化)。任何想法如何做到这一点? 应该是类似的东西:替换句子中的第n个词

function formatNumber(txt){ 
    return txt.replace(3rd-word, formatNumber(3rd-word)); 
} 
+0

为什么你不只是匹配第一组数字? – epascarello

+1

“单词”是什么意思?在许多语言中,单词不是由空格分隔的,因此寻找单词边界[并非微不足道](http://en.wikipedia.org/wiki/Text_segmentation)。 –

回答

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! 
+0

这不会取代第三个词,它将取代第三个词的第一个出现。尝试句子''与我们在他们的巴士'''... – Guffa

+0

它仍然不会取代第三个词,它取代了第三个词的第一个出现。 – Guffa

+0

为什么'formatterFunction.call(undefined,match)'而不是简单的'formatterFunction(match)'? –

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; 
} 

演示: http://jsfiddle.net/Guffa/5yA62/

+0

这只会匹配'-1.2345e9'中的'1',这可能不是OP在寻找“一个号码。” –

+0

@MikeSamuel:这是可能的,但问题并不清楚。答案的第一句提到了这个限制。 – Guffa

0

将其分解为若干部分。

  • 创建一个函数,将您的单词转换为所需的格式。
  • 将你的句子分解成单词。
  • 针对适当的单词运行该功能。
  • 将单词放回句子中。

这并不能解决您的问题。你仍然需要找到一种方式,你选择格式化数字,但它解决了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" 

它可能有问题,如果你的句子比一个空格一些更复杂的结构分离你想要维护的词...