簡體   English   中英

替換句子中的第n個單詞

[英]Replace nth word in sentence

我有一個獲取字符串的函數,我正在尋找一種格式化第三個單詞(即數字,我想用逗號對其進行格式化)的方法。 知道怎么做嗎? 應該是這樣的:

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

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

將其分為幾部分。

  • 創建一個函數,將您的單詞轉換為所需的格式。
  • 將句子分成單詞。
  • 針對適當的單詞運行該功能。
  • 將單詞重新放入句子中。

這不能解決您的問題。 您仍然需要找到一種選擇格式的數字格式,但這解決了將第三個單詞大寫的類似問題:

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"

如果您的句子的結構比您要維護的單詞的單個空格分隔更復雜,則可能會出現問題...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM