Reputation: 4783
Suppose the string:
"The | dog";
If I do in js:
var string;
string = "The | dog | and | apple";
string.split("|")[1];
The returns will be "dog". I should like to replace that, somelike this:
string.split("|")[1] = "cat";
And the string pass to be "The | cat | and |apple", knowing as string "dog" can be another value too.
It's possible?
Upvotes: 0
Views: 11069
Reputation: 141827
You can replace the individual array element and then use join to make a string again:
var string = "The | dog";
var DELIMITER = " | ";
var parts = string.split(DELIMITER);
parts[1] = "cat";
string = parts.join(DELIMITER);
// string === "The | cat"
Upvotes: 4
Reputation: 6570
var arr=string.split('|');
arr[1]='cat'
var s=arr.join('|');
or using regular expressions
string.replace(/^([^\|]+)\|([^\|]+)/g,'$1|cat')
Upvotes: 2