Nicolas Leucci
Nicolas Leucci

Reputation: 3369

Add variable into string

All I need to do here is to add a variable before each specific string.

Example:

var exampleString = "blabla:test abcde 123test:123";
var formattedString = "el.blabla:test abcde el.123test:123";

As you can see, when I have something like "XXX:XXX", I need to add a variable before it.

I have the Regex to find "XXX:"

var regex = new RegExp(/\w+([aA-zZ]:)/g)

But when I try to replace it, it replaces all instead of adding the variable "el."

var exampleString = "blabla:test abcde 123test:123";
var formattedString = exampleString.replace(new RegExp(/\w+([aA-zZ]:)/g), 'el.');
// formattedString is now "el.test abcde el.123"
// Instead of "el.blabla:test abcde el.123test:123"

Could anyone makes this work ? Thanks :)

Source: Javascript Regex: How to put a variable inside a regular expression?

Upvotes: 0

Views: 181

Answers (4)

Alessandro
Alessandro

Reputation: 4472

You should use a function like insertAt instead replace, see following example:

String.prototype.insertAt=function(index, string) { 
  return this.substr(0, index) + string + this.substr(index);
}

var exampleString = "blabla:test abcde 123test:123";
var regex = new RegExp(/\w+([aA-zZ]:)/g)
var formattedString = exampleString;

while ( (result = regex.exec(exampleString)) ) {
    formattedString = formattedString.insertAt(result.index, "el.");
}

console.log(formattedString);

I hope it helps you, bye.

Upvotes: 0

var exampleString = "blabla:test abcde 123test:123";
var formattedString = exampleString.replace(/\w*:\w*/gi, 'el.$&');
console.log(formattedString);

Regex use and Explanation Here https://regex101.com/r/U2KeXi/3

Sample Fiddle here https://jsfiddle.net/a8wyLb0g/2/

Upvotes: 3

Barmar
Barmar

Reputation: 782785

You need to use ^ to match only at the beginning. And remove the g modifier, since you only want to replace once, not every time.

There's also no reason to use new RegExp(), just use a RegExp literal.

In the replacement string, you need to use $& to copy the original string into the replacement.

var exampleString = "blabla:test abcde 123test:123";
var formattedString = exampleString.replace(/^\w+[a-z]:/i, 'el.$&');
console.log(formattedString);

Also, the proper way to match all letters in either case is with [A-Za-z], not [aA-zZ], or use the i modifier to make the regexp case-insensitive. Your regexp matches all characters in the range A-z, which includes lots of punctuation characters that are between the uppercase letters and lowercase letters in the ASCII code.

Upvotes: 1

binariedMe
binariedMe

Reputation: 4329

Just use this

exampleString.replace(/(\w*):(\w*)/gi, 'el.$1:$2');

REGEXP explanation :

capturing group (\w*) is for capturing any alphabets in any number of occurance, $1 and $2 specifies the first and second capturing group.

Upvotes: 0

Related Questions