用jQuery /JavaScript替換最后一個索引

[英]Replace last index of , with and in jQuery /JavaScript


i want to replace the last index of comma (,)in string with and.

我想用and替換字符串中逗號(,)的最后一個索引。

eg . a,b,c with 'a,b and c'

如。a b c和a b c

eg q,w,e with q,w and e

q w e和q w e

5 个解决方案

#1


10  

DEMO

演示

lastIndexOf finds the last index of the parameter string passed in it.

lastIndexOf查找傳入參數字符串的最后一個索引。

var x = 'a,b,c';
var pos = x.lastIndexOf(',');
x = x.substring(0,pos)+' and '+x.substring(pos+1);
console.log(x);

you can also use this function

你也可以使用這個函數

function replace_last_comma_with_and(x) {
    var pos = x.lastIndexOf(',');
    return x.substring(0, pos) + ' and ' + x.substring(pos + 1);
}
console.log(replace_last_comma_with_and('a,b,c,d'));

#2


7  

This regex should do the job

這個regex應該完成這項工作

"a,b,c,d".replace(/(.*),(.*)$/, "$1 and $2")

#3


2  

Try the following

試試以下

var x= 'a,b,c,d';
x = x.replace(/,([^,]*)$/, " and $1");

#4


0  

Try

試一試

var str = 'a,b,c', replacement = ' and ';
str = str.replace(/,([^,]*)$/,replacement+'$1'); 

alert(str)

Fiddle Demo

小提琴演示

#5


0  

A simple loop will help you out

一個簡單的循環將幫助您解決這個問題

first find the index of all , in your string using,

首先找到所有的索引,在你的字符串中,

var str = "a,b,c,d,e";
var indices = [];
for(var i=0; i<str.length;i++) {
    if (str[i] === ",") indices.push(i);
}


indices = [1,3,5,7] as it start from 0

len = indices.length()
str[indices[len - 1]] = '.'

This will solve your purpose.

這將解決你的目標。


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2013/08/01/f3cbd92d90ba7e382940ed9071557a41.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com