Suppose I have string variable such as:
var a = "xxxxxxxxhelloxxxxxxxx";
or:
var a = "xxxxhelloxxxx";
I want to insert "world"
after "hello"
.
I can't use substr()
because the position is not known ahead of time. How can I do this in JavaScript or jQuery?
The splice() method is used to insert or replace contents of an array at a specific index. This can be used to insert the new string at the position of the array. It takes 3 parameters, the index where the string is to be inserted, the number of deletions to be performed if any, and the string to be inserted.
In Java, two strings can be concatenated by using the + or += operator, or through the concat() method, defined in the java.
Python add strings with + operator The easiest way of concatenating strings is to use the + or the += operator. The + operator is used both for adding numbers and strings; in programming we say that the operator is overloaded. Two strings are added using the + operator.
var a = "xxxxhelloxxxxhelloxxxx";
a = a.replace(/hello/g,"hello world"); // if you want all the "hello"'s in the string to be replaced
document.getElementById("regex").textContent = a;
a = "xxxxhelloxxxxhelloxxxx";
a = a.replace("hello","hello world"); // if you want only the first occurrence of "hello" to be replaced
document.getElementById("string").textContent = a;
<p>With regex: <strong id="regex"></strong></p>
<p>With string: <strong id="string"></strong></p>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With