Yoshi
Yoshi

Reputation: 11

How can I replace specific word combinations in a string in Javascript?

I am currently learning javascript, and trying to automate a program that automatically detects unshortened acronyms and replaces it in a body of text. For example, let's say I want all "Lord of the Rings" phrases to be replaced with LotR.

I am trying

string = string.replace("the Lord of the Rings", "LotR");

but it doesn't seem to do anything. Maybe I should look into string.search() function instead, even if it seems to take more steps? Any help would be greatly appreciated!

Upvotes: 0

Views: 935

Answers (4)

RobKohr
RobKohr

Reputation: 6953

If you want to replace all instances of the word with the acronym, you should do:

let str = 'Lord of the Rings is the best movie series ever, and Lord of the Rings is also a series of books. ';

let result = str.replaceAll("Lord of the Rings", "LotR");

String.replaceAll() is supported by most modern browsers, but you can check if it is supported on your target platform using caniuse.com.

You can also do str.split("Lord of the Rings").join("LotR") if you want to make it more backwards compatible.

Or you can use regular expressions:

str.replace(/the Lord of the Rings/g, "LotR");

And if you want to make it so the replacement is insensitive to case:

str.replace(/the Lord of the Rings/ig, "LotR");

Upvotes: 0

Sahadat Hossain
Sahadat Hossain

Reputation: 4379

You can use the replace() method to replace all occurrences of a word or substring inside another string.

Let's check out the code :

<script>
    var myStr = "the Lord of the Rings";
    var newStr = myStr.replace(/the Lord of the Rings/g, "LotR");
    
    // Printing the modified string
    document.write(newStr);
</script>

Upvotes: 1

UraniumSteel
UraniumSteel

Reputation: 67

I would not use string as a variable.

Also you do not show what string is initialized to. example

var mystring = "I like the movie the Lord of the Rings";
mystring = mystring.replace("the Lord of the Rings","LotR");

Mystring now contains "I like the movie LotR"

Upvotes: 0

sonEtLumiere
sonEtLumiere

Reputation: 4572

You need first to declare your variable to apply replace() method, try this:

let str = "the Lord of the Rings";
str = str.replace("the Lord of the Rings", "LotR");
console.log(str)

If you want to match every "the Lord of the Rings" in your string, you can use a global flag (g) into the first argument in replace():

let str = "the Lord of the Rings the Lord of the Rings";
str = str.replace(/the Lord of the Rings/g, "LotR");
console.log(str)

Upvotes: 0

Related Questions