简体   繁体   中英

Replace all occurences of “-” between numbers with “:” in javascript

I have a string which looks like this:

1,87-99,88:12,sds-554,sdsd,787,99-145

If a "-" appears in the middle of 2 numbers, I want to change it to a ":". What is the shortest way to do this in javascript? Thanks for help.

try:

text='1,87-99,88:12,sds-554,sdsd,787,99-145';
tex2=text.replace(/(\d)-(\d)/g,'$1:$2');
console.log(tex2);

example: http://jsfiddle.net/bingjie2680/Wcptr/

Here's my variant.

var a = '1,87-99,88:12,sds-554,sdsd,787,99-145'
var b = a.replace(/(\d)-(\d)/g,'$1:$2')

$1 and $2 puts matched digits back into string.

Try

'1,87-99,88:12,sds-554,sdsd,787,99-145'.replace(/(\d)-(\d)/g, '$1:$2'));​

http://jsfiddle.net/ZK9Mj/

var a = '1,87-99,88:12,sds-554,sdsd,787,99-145'
var b = a.replace(/(\d)-(\d)/g, '$1:$2');

"b" will give you what you want

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM