简体   繁体   中英

Javascript multiple replace with regex that avoids html tags

So I have a java script that finds vowels and capitalizes them. What I want to do is create a id called bigBlue that changes the capitalized values into blue characters with specific css properties.

var strMessage1 = Emphathy;
var startDiv = '<div id="bigBlue">';
var endDiv = '</div>';
var newRoot = strMessage1
.replace(/a/g, startDiv+'A'+endDiv)
.replace(/e/g, startDiv+'E'+endDiv)
.replace(/i/g, startDiv+'I'+endDiv)
.replace(/o/g, startDiv+'O'+endDiv)
.replace(/u/g, startDiv+'U'+endDiv)
$("#test").append(newRoot);

Here is the with the result JsFiddle

My output is pretty much broken gibberish. What im thinking is that the .replace is also replacing the properties of the startDiv and endDiv.

How do I avoid the replacement of the startDiv and endDiv values, while replacing the vowels with the capital vowels, inclosed in the big blue div?

try use function to replace instead direct symbols like that

var newRoot = strMessage1.replace(/[aeiou]/g, function(sym){return startDiv+sym.toUpperCase()+endDiv});

sample on jsfiddle

if you want that chars was on one line - use <span> instead of <div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM