Замена слова в строке на определенной позиции
Никак не могу придумать способ заменить слово в строке на нужно позиции. Например, есть строка:
Код:
<meta http-equiv="content-type" content="text/html; charset=utf-8" /> |
function nthReplace(str, regex, newValue, n) {
return str.replace(regex, function(a) { return (--n == 0) ? newValue : a; });
}
alert(nthReplace("content 1 content 2 content 3", /content/g, "****", 2));
|
Яростный Меч,
Интересно :) Я не уточнил, что известен индекс положения в строке заменяемого слова. Ну вобщем как-то вот так я сделал.
var sub = 'content';
var str = '<meta http-equiv="content-type" content="text/html; charset=utf-8" />';
var rep = '%%5%%';
var index = 32;
str = str_replace(str, sub, rep, index)
alert(str)
function str_replace(str, sub, rep, index){
str = str.split('');
str.splice(index, sub.length, rep);
return str.join('');
}
|
var str = '<meta http-equiv="content-type" content="text/html; charset=utf-8" />'; str = str.replace(/(.+)content="(.+);(.+)/, '$1content="ololo;$3'); alert(str); :D |
| Часовой пояс GMT +3, время: 15:53. |