Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding a substring and inserting another string

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?

like image 216
Charles Yeung Avatar asked May 03 '11 05:05

Charles Yeung


People also ask

How do you add a string to a specific index?

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.

How do you add one string to another in Java?

In Java, two strings can be concatenated by using the + or += operator, or through the concat() method, defined in the java.

How do you insert a string in Python?

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.


1 Answers

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>
like image 171
gion_13 Avatar answered Sep 16 '22 15:09

gion_13