issue with replace() method in javascript when replacing spaces - javascript

This is the function I am working with:
function replaceH1s() {
$("h1").each(function(){
h1name = $(this).text();
stuff = h1name.toLowerCase().replace(' ','-');
$(this).html('<img src="/assets/image/h1_' + stuff + '.png" alt="' + h1name + '" />');
})
}
I can't figure out for the life of me why this function replaces the first space in h1name string with a hyphen, but not any of the subsequent ones. I tried unescaping and escaping (and then replacing %20 it stumbles upon with hyphens, but that did the same thing). I tried regular expressions for catchall whitespace and that did the same thing. I feel like I am not seeing something super fundamental here.

You need to specify a global regular expression. Otherwise it only matches the first occurrence.
// regular expression
function replaceH1s() {
$("h1").each(function(){
h1name = $(this).text();
stuff = h1name.toLowerCase().replace(/\s+/g, '-'); // matches all whitespace
// use / /g to match a single space
$(this).html('<img src="/assets/image/h1_' + stuff + '.png" alt="' + h1name + '" />');
})
}
// firefox only
function replaceH1s() {
$("h1").each(function(){
h1name = $(this).text();
stuff = h1name.toLowerCase().replace(' ', '-', 'g');
$(this).html('<img src="/assets/image/h1_' + stuff + '.png" alt="' + h1name + '" />');
})
}

stuff = h1name.toLowerCase().replace(/ /g, '-');

The replace function was designed to only replace the first instance of the string you are searching for. If you want to replace all instances, then using regular expressions would work better.
take a look at this page for more information.

If you were trying to replace all spaces with - your close but not quite there
The replace function in JavaScript only replaces the first value it finds that matches and quits. Here is a replaceAll function.
stuff = h1name.toLowerCase().replace(' ' + /g, '-');​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
alert(stuff); //make sure this is what you want
the /g specifies replace all.

Related

indexOf for multiple options

Let say, I get the following using var content = this.innerHTML:
w here </div>
Using indexOf (or other ways), I want to check for the first position that has either "Space", "<" or "&nbsp".
In this case, it will be 1 (after "w").
What I am confused about is how do I check for the very first position that has either one of these three choices? Do I use Do...while to check for individual "options"?
You're probably looking for a Regular Expression (Regex) and the String#search method. Regex is a bit much to learn all at once, but I'll explain this example code.
You can use square brackets to denote a set of characters, so for example [ <] says "match either a space or a less-than sign."
You can use the pipe | to separate possibilities if you want to match one pattern or another, and that's how to account for matching a non-breaking space HTML entity.
var string = 'w here </div>',
index = string.search(/[ <]| /)
console.log(index) //=> 1
You can use a regular expression with alternations (|), which means "match one of these things". That will also tell you what you found, if that's useful:
function check(str) {
var m = / |<| /.exec(str);
if (!m) {
console.log("Not found in '" + str + "'");
return;
}
console.log("'" + m[0] + "' found at index " + m.index + " in '" + str + "'");
}
check("w here </div>");
check("where </div>");
check("where</div>");

Js replace and Regex exclude a word

I have this issue with regex, it doesn't really have friendly syntax for me :(.
Basically I need to match some text and wrap the matched word/letter with a <strong>.
html = html.replace(new RegExp('(' + word + ')', 'ig'), function ($1, match) {
return '<strong>' + match + '</strong>';
Now everything works fine except that in some occasion, the previously added <strong> get matched to messing up the html.
So I basically need the html.replace function to ignore any <strong> word during the matching.
I have tried to change new RegExp('(' + word + ')' with new RegExp('(?!\<strong\>)(' + word + ')' but I still have issue.
Ex.
'<strong>Alpinestars</strong> SMX Plus Gore-Tex Boots'.replace(new RegExp('(o)(?!</strong>)', 'ig'), function ($1, match) {
return '<strong>' + match + '</strong>';});
returns
"<str<strong>o</strong>ng>Alpinestars</str<strong>o</strong>ng> SMX Plus G<strong>o</strong>re-Tex B<strong>o</strong><strong>o</strong>ts"
You can check if you are not inside an element node with (?![^>]*>) look-ahead:
function escapeRegExp(string){
return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
var key = 'o';
var s = '<strong>Alpinestars</strong> SMX Plus Gore-Tex Boots';
var res = s.replace(RegExp(escapeRegExp(key) + '(?![^>]*>)', 'ig'), function (m) {
return '<strong>' + m + '</strong>';});
document.getElementById("t").innerHTML = res.replace(/>/g, ">").replace(/</g, "<");
<div id="t"/>
You also do not need any capturing groups (unless you are using alternations like boots|caps|hats) and do not have to use new with RegExp. I also added an escapeRegExp function from MDN to escape special characters in key if any.
You were close. You just had the order wrong. According to the following mdn page, the x(?!y) means: Matches x only if x is not followed by y.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp
So, this seems to work for me:
var word = 'and';
'dogs <strong>and</strong> cats <strong>and</strong>'.replace(
new RegExp('(' + word + ')(?!</strong>)', 'ig'),
function ($1, match) {
return '<strong>' + match + '</strong>';
}
);

Replace illegal character in javascript string with the legal one

how do I replace illegal character in a javascript code? I found a lot of solution to strip them off the string but none to actually keep the char there.
here an example line:
document.getElementById("popupcontent").innerHTML += "<img class='popupbanner' src='" + eventcontent[date][i]['bannerimg'] + "' />";
So in my function, it make my "for" loop not working properly as soon as the following char are in a string: <, >, /
any help is appreciated.
regards,
You can replace characters in javascript using the replace() function. Please see this stackoverflow post.
You can have the browser automatically escape the stuff for you:
function escape(string) {
var target = document.createElement('div');
target.appendChild(document.createTextNode(string));
return target.innerHTML;
}
Then use it by:
var escapedString = escape(eventcontent[date][i]['bannerimg']);
document.getElementById("popupcontent").innerHTML += "<img class='popupbanner' src='" + escapedString + "' />";

JavaScript: Replace last occurrence of forward slash

I've tried fiddling with
replace(/_([^_]*)$/,replacement+'$1')
from another post but can't get it to work
I have a string:
<div class="plus"></div><div class="details"></div>text1/text2
that I want to transform into
<div class="plus"></div><div class="details"></div>text1/<br>text2
but I keep getting the / in /div replaced as well
Anyone?
Edit: To be clear I want to replace the last
"/"
with
"/<br>"
only the last occurance.
I dunno... maybe I'm better off going back in my code and try to replace the slash before prepending with html...
Use lastIndexOf() method
var index = str.lastIndexOf('/');
str = str.substr(0, index + 1) + "<br>" + str.substr(index + 1);
Here is the fiddle
Try
'<div class="plus"></div><div class="details"></div>text1/text2'.replace(/(\/)([^\/]*)$/, '$1' + '<br />' + '$2' )
If you're not trying to capture the slash in the back-reference, add the slash into the text itself:
replace(/_([^_]*)$/,replacement+'$1/')
-----------------------------------^
It's easier to do that using string methods:
var index = str.lastIndexOf('/');
str = str.substr(0, index) + str.substr(index + 1);

Regular expression for replacing string with javascript

I need help in writing regular expression:
part of my string is fixed and another part of its variable.
only if fixed AND variable string exist i need to alter the string other wise no.
Fixed string:example: AA.BBB.COM
Variable string (may or mayn't exist ): US, but if exist it will be always two letter string with any combination of letter.
In below string if I have variable two letter string exist I want to append “.new”
1 ) https://XY**.US**.AA.BBB.COM
Output: https:// XYZ12**.US.NEW**.AA.BBB.COM
2 ) https://XY.UK.AA.BBB.COM
Output: https:// XYZ12.UK.NEW.AA.BBB.COM
3) https://XY.AA.BBB.COM (no variable string so no change)
Output: https:// XY.AA.BBB.COM
Thanks for your help .
Raghav
Something like the following should get you started, there are other methods. Splitting and parsing might suit better depending on your real requirements:
var s = 'https://XY.US.AA.BBB.COM';
var t = 'https://XY.UK.AA.BBB.COM';
var u = 'https://XY.AA.BBB.COM';
var re = /(\.)(UK|US)(\.)/;
alert(
s.replace(re, '$1' + '$2' + '.NEW' + '$3') + '\n' +
t.replace(re, '$1' + '$2' + '.NEW' + '$3') + '\n' +
u.replace(re, '$1' + '$2' + '.NEW' + '$3')
);

Categories

Resources