how to replace multiple words using javascript replace() function? - javascript

here is my code:
var keys = keyword.split(' ');
//alert(keys);
for(var i=0; i<keys.length; i++)
{
var re = new RegExp(keys[i], "gi");
var NewString = oldvar.replace(re, '<span style="background-color:#FFFF00">'+keys[i]+'</span>');
document.getElementById("wordlist").innerHTML=NewString;
alert(keys[i]);
}
but here if I put a string "a b"; its split into two letters "a" and "b"
and this replace function replace "a" but when it get "b" it overwrite and only replace "b".
but I want to highlight both "a" and "b".
how to solve this?
I got another problem . If I replace/highlight it then it replace all "a" and "b" of HTML tag. so, how to prevent to replace those html tag. but also when I display the whole text I need all html tag

You can actually do a single regex replace like this:
var re = new RegExp(keys.join("|"), "gi");
oldvar = oldvar.replace(re, replacer);
document.getElementById("wordlist").innerHTML = oldvar;
function replacer(str)
{
return '<span style="background-color:#FFFF00">' + str + '</span>';
}
Example - http://jsfiddle.net/zEXrq/1/
What it is doing is merging all keys into a single regex seperated by | which will match all the words then running the replacer function on the matches.
Example 2 - http://jsfiddle.net/zEXrq/2/

var keys = keyword.split(' ');
//alert(keys);
for(var i=0; i<keys.length; i++)
{
var re = new RegExp(keys[i], "gi");
oldvar = oldvar.replace(re, '<span style="background-color:#FFFF00">'+keys[i]+'</span>');
document.getElementById("wordlist").innerHTML=oldvar;
alert(keys[i]);
}
Edit:
It seems obvious that oldvar is not changed durring the loop always only last replace is applyied. You have to change "oldvar" in order to replace all the words

You should do the Operations on the same var. You take oldvar outside of the loop, but never take the changed content into oldvar. So the last iteration (only) is the one which replaces the content.

You're calling replace on the variable oldvar (which is not declared in this snippet) in each iteration and thus starting from the same point - the non-highlighted string - every time. Without having seen all of the code, I would guess that simply replacing var NewString = with oldvar = and .innerHTML=NewString with .innerHTML=oldvar will solve your problem.

Related

Removing commas unless inside quotes, not using regexp

I am trying to remove commas in a string unless they appear inside quotes.
var mystring = "this, is, a, test, example, \"i, dont know\", jumps" ;
var newchar = '';
mystring = mystring.split(',').join(newchar);// working correctly
document.write(mystring);
Output I have is
this is a test example "i dont know" jumps
Expected output
this is a test example "i, dont know" jumps
A couple of questions. How can I find the index of string so that inside the quotation it will include comma but outside of quotation " it will not include comma ,. I know I have to use indexOf and substring but I don't know how to format it? (No regex please as I'm new to JavaScript and I'm just focusing on the basics.)
Loop through the string, remembering whether or not you are inside a set of quotation marks, and building a new string to which the commas inside quotes are not added:
var inQuotes = false; // Are we inside quotes?
var result = ''; // New string we will build.
for (var i = 0; i < str.length; i++) { // Loop through string.
var chr = str[i]; // Extract character.
var isComma = chr === ','; // Is this a comma?
var isQuote = chr === '"'; // Is this a quote?
if (inQuotes || !isComma) { // Include this character?
if (isQuote) inQuotes = !inQuotes; // If quote, reverse quote status.
result += chr; // Add character to result.
}
}
This solution has the advantage compared to the accepted one that it will work properly even if the input has multiple quotes strings inside it.
This will work, but it's not ideal for all cases. Example: It will not work for a string with more than 2 quotation marks.
var mystring = "this, is, a, test, example, \"i, dont know\", jumps" ;
var newchar = '';
var firstIndex = mystring.indexOf("\"");
var lastIndex = mystring.lastIndexOf("\"");
var substring1 = mystring.substring(0,firstIndex).split(',').join(newchar);
var substring2 = mystring.substring(lastIndex).split(',').join(newchar);
mystring = substring1 + mystring.substring(firstIndex, lastIndex) + substring2;
document.write(mystring);
Some day you need to start using regexp, than regexr.com is your friend. The regexp solution is simple:
var mystring = "this, is, a, test, example, \"i, dont know\", jumps" ;
var newchar = '_';
mystring = mystring.match(/(".*?"|[^",\s]+)(?=\s*,|\s*$)/g).join(newchar);// working correctly
document.write(mystring);

Regex match quotes inside bracket regex

I'm working on a regex that must match only the text inside quotes but not in a comment, my macthes must only the strings in bold
<"love";>
>/*"love"*/<
<>'love'<>
"lo
more love
ve"
I'm stunck on this:
/(?:((\"|\')(.|\n)*?(\"|\')))(?=(?:\/\**\*\/))/gm
The first one (?:((\"|\')(.|\n)*?(\"|\'))) match all the strings
the second one (?=(?:\/\**\*\/)) doesn't match text inside quotes inside /* "mystring" */
bit my logic is cleary wrong
Any suggestion?
Thanks
Maybe you just need to use a negative lookahead to check for the comment end */?
But first, I'd split the string into separate lines
var arrayOfLines = input_str.split(/\r?\n/);
or, without empty lines:
var arrayOfLines = input_str.match(/[^\r\n]+/g);
and then use this regex:
["']([^'"]+)["'](?!.*\*\/)
Sample code:
var rebuilt_string = ''
var re = /["']([^'"]+)["'](?!.*\*\/)/g;
var subst = '<b>$1</b>';
for (i = 0; i < arrayOfLines.length; i++)
{
rebuilt_string = rebuilt_string + arrayOfLines[i].replace(re, subst) + "\r\n";
}
The way to avoid commented parts is to match them before. The global pattern looks like this:
/(capture parts to avoid)|target/
Then use a callback function for the replacement (when the capture group exists, return the match without change, otherwise, replace the match with what you want.
Example:
var result = text.replace(/(\/\*[^*]*(?:\*+(?!\/)[^*]*)*\*\/)|"[^"\\]*(?:\\[\s\S][^"\\]*)*"|'[^'\\]*(?:\\[\s\S][^'\\]*)*'/g,
function (m, g1) {
if (g1) return g1;
return '<b>' + m + '</b>';
});

Javascript: using String.replace() to replace/remove HTML anchors

I am trying to accomplish a task that would be very simple if there was a way to replace one simple string with another.
I have an HTML source of a page as a string. It contains several internal anchors such as
<a href="#about">, <a href="#contact">, <a href="#top">, <a href="#bottom">, <a href="#who-we-are">, etc.
All of the anchors are stored in an array (['about','contact'],...), and I need to remove every occurance of a string like
href="#whatever"
(where whatever is each time something different) so that the result is
<a>
What I'd do with simple search and replace would be to iterate through my array and replace each occurance of
'href="'+anchorname+'"'
with an empty string. But after many attempts with string.replace() I still have't found the way to accomplish this.
In other words (posted also in the comments):
A much simpler way to put my question would be this:
Suppose my string contains the following three strings
<a href="#contact"> <a href="#what"> <a href="#more">
How to I use Javascript to replace them (but NOT any tag with the same pattern) with <a> ?
All of the anchors are stored in an array (['about','contact'],...), and I need to remove every occurance of a string like href="#whatever" (where whatever is each time something different) so that the result is
for this you could do something like this:
var tets_array = $("a[href^='#']"); // select all a tags having href attr starting with #
Then take the array and modify with what you want.
I don't know if I understand the question but you can try this :
var index = myArray.indexOf('whatever');
myArray[index] = "whatever2"
One specific statement would be as follows:
var mystring = '<a href="#thistag"> <a href="#thattag">';
var repstring = mystring;
var myarray = ['thistag', 'theothertag'];
for (var i = 0; i < myarray.length; i++) {
var reptag = myarray[i];
repstring = repstring.replace('a href="#' + reptag + '"', 'a');
}
Then repstring contains the final string. Note the alternating single and double quote characters which ensure that the double-quotes are in their usual place as part of the HTML text. Obviously you can change reptag (i.e., the content of myarray) to include the # character, at which point you would alter the mystring.replace(...) line to match.
If I understand you correctly then you can replace all of those using regular expressions.
var tagString = '<a href="#contact"> <a href="#what"> <a href="#more">';
// Find every occurrence which starts with '#' and ends with '"'
var regEx = new RegExp('#.*?"', 'g');
// Replace those occurrences with '"' to remove them
tagString = tagString.replace(regEx, '"');
EDIT:
To replace specific tags in an array, you can do the following:
var tags = ['<a href="#a">', '<a href="#b">', '<a href="#c">'];
var tagsToReplace = ['a', 'c'];
for (var i = 0, len = tags.length; i < len; i++) {
var matches = tags[i].match(/#.*"/);
if (matches === null) {
continue;
}
var anchor = matches[0].substr(1).replace('"', ''); // Get only the anchor
if (tagsToReplace.indexOf(anchor) !== -1) {
tags[i] = tags[i].replace('#' + anchor, 'replaced');
}
}
Thanks for all of the suggestions. I tried various variations of them and noticed that some worked in Firefox but not in chrome, which led me to this thread
Why doesn't the javascript replace global flag work in Chrome or IE, and how to I work around it?
Which led me to the solution:
for (var i=0; i < myTags.length ; i++)
{
var find = 'href="#' + myTags[i] + '"';
var regex = new RegExp(find, 'gi');
MyWholeString = MyWholeString.replace(regex, '');
}

Extracting Strings Into an Array Regex

I'm almost there! Just can't figure out the last part of what I need... forming the array.
I want to go through an html file and extract url's from between the phrases playVideo(' and ')
For testing purposes I am just trying to get it to work on the variable str, eventually this will be replaced by the html document:
<script type="text/javascript">
var str ="playVideo('url1') BREAK playVideo('url2') BREAK playVideo('url3')";
var testRE = str.match("playVideo\\(\'(.*?)\'");
alert(testRE[1]);
</script>
This will output 'url1' but if I change it to alert(testRE[2]) it is undefined. How can I get it to fill out the array with all of the URLs (eg testRE[2] output 'url2' and so on) ?
Thanks for any help, new to regex.
Cannot comment, why is that, but adding that by iterating on the regex you get access to the groups;
var str ="playVideo('url1') BREAK playVideo('url2') BREAK playVideo('url3')";
var re = /playVideo\('(.*?)'\)/g;
while (match = re.exec(str)) {
alert(match[1]);
}
Normally a javascript regular expression will just perform the first match. Update your regular expression to add the g modifier. Unfortunately JavaScript regular expressions don't have a non-capturing group so you have to do a little more processing to extract the bit you want e.g.
<script type="text/javascript">
var str ="playVideo('url1') BREAK playVideo('url2') BREAK playVideo('url3')";
var testRE = str.match(/playVideo\(\'[^']*\'/g);
var urls = [];
for (var i = 0; i < testRE.length; i++)
{
urls[i] = testRE[i].substring(11).match(/[^']*/);
}
alert(urls[1]);
alert(urls[2]);
</script>

group parts of a string into an array element

If I have a string... abcdefghi
and I want to use regex to load every elemnent into an array but I want to be able to stick anything connected by plus sign into the same element... how to do that?
var mystring = "abc+d+efghi"
output array ["a","b","cde","f","g","h","i"]
One way to do it:
var re = /([^+])(?:\+[^+])*/g;
var str = 'abcd+e+fghi';
var a = str.match(re).map(function (s) { return s.replace(/\+/g, ''); });
console.log(a);
The value of a[3] should now be 'def'.
http://jsfiddle.net/rbFwR/2
You can use this expression, to produce [a][b][c+d+e][f][g][h][i].
mystring.split ("(.\+)*.")
Next, replace any + characters with empty on the resulting list.
mystring.split("\\+")
Click here for more information.

Categories