JS正则匹配某符号与符号之间内容

RT,我有一段字符串'1|AUD/USD|SPOT|TMU|1000000'|符号之间的内容不定,请教如何利用正则和replace()方法任意替换某两个|符号之间的内容?

例如
'1|AUD/USD|SPOT|TMU|1000000' => '1|EUR/USD|SPOT|TMU|1000000'
'1||SPOT|TMU|1000000' => '1|CAD/USD|SPOT|TMU|1000000'

阅读 3k
3 个回答

感觉还是分割简单点。

var mySymbol = '|';
var arr = '1|AUD/USD|SPOT|TMU|1000000'.split(mySymbol);
arr[1]='EUR/USD';
arr.join(mySymbol);
"1|EUR/USD|SPOT|TMU|1000000"
str.replace(/\|([A-Za-z0-9_]+)\|/ig, '|test|')
// let str = '1|EUR/USD|SPOT|TMU|1000000';
let str = '1||SPOT|TMU|1000000';

console.log(str);

str = str.split('|').map((value, index) => {
    if (index === 1) {
        if (!value) {
            return 'CAD/USD'
        } else if (value === 'AUD/USD') {
            return 'EUR/USD'
        }
    }
    return value;
}).join('|')

console.log(str);
推荐问题
宣传栏