问题描述:

I would like to add to the current string using javascript. Currently, It is working fine but I am doing it in a very dirty way currently. I am basically replacing the WHOLE string instead of just adding to it. Is there a way that I can just add a comma and continue my string?

JS:

var mystring = "'bootstrap'"

console.log(mystring.replace(/bootstrap/g , "'bootstrap', 'bootstrap2', 'bootstrap3'"));

JSFiddle

网友答案:

You can add to the end of a string by using the +=operator. See the docs regarding string operators.

var mystring = "'bootstrap'"
mystring += ", 'bootstrap2'";
mystring += ", 'bootstrap3'";
console.log(mystring);
网友答案:

You can concatenate( + operator ) instead of replace if you just want the second string to get appended to the first string.

var mystring = "'bootstrap'"
var newString = mystring +", "+ "'bootstrap', 'bootstrap2', 'bootstrap3'";
console.log( newString );
网友答案:

What about:

mystring += "'bootstrap2',";

or

var arr = ["str1", "str2", "str3"];
var mystring = arr.map((e)=>{return "'"+e+"'";}).join(",")

Array.map function used to wrap each string with single quates, than you Array.join - used to put "," between members

网友答案:

You can concat strings with the + operator:

var mystring = "'bootstrap'" + ",";
console.log(mystring);
网友答案:

Use an array and the join method.

var arr = [];
var myString = "bootstrap";

arr.push(myString);
arr.push(myString);
arr.push("other string");
arr.push("bootstrap");

// combine them with a comma or something else
console.log(arr.join(', '));
网友答案:

It is not suggested, but if you want to keep symbols and not care about order, and want to only add to a string beginning with 'bootstrap':

myString = "'bootstrap'";
console.log(myString.replace(/^(?='(bootstrap)')/, "'$12', '$13', "));
相关阅读:
Top