JavaScript string replace() not working when replacing variable - javascript

I'm trying to create a JavaScript script for highlighting certain text on a page. Right now I'm having issues trying to replace text (from the body html) with other text. I want to replace all instances of each item in the array highlights with some other text.
The code that I'm using is:
var responseText = server.responseText;
var highlights = responseText.split("\n");
var text = document.body.innerHTML;
for (i in highlights) {
if (highlights[i].length > 1) {
var exp = new RegExp(highlights[i], "g");
console.log(exp);
console.log(highlights[i]);
text = text.replace(exp, "XXXXXXXXXXX");
}
}
document.body.innerHTML = text;
Currently, I am getting the correct value printouts for highlights[i] and I think I am for the regular expression exp; if highlights[i] is 'Remember', then the printout I'm getting for exp is '/Remember/g' (without the quotation marks) -- but it's not replacing the word 'Remember' on the page. 'And if I replace highlights[i] in the new RegExp() with simply the string "Remember" it works correctly. Any ideas on what's wrong?
EDIT:
I solved the problem! When creating the RegExp() I passed in highlights[i].trim() instead of just highlights[i] to get rid of whitespace at the beginning/end and it appears to be working now.

There is some problem with your multiline server.responseText .
I replaced the input with spaces instead of newlines, and all the replacements work fine :
http://jsfiddle.net/XTdgJ/1/

Related

How can I ltrim and rtrim select characters in Javascript?

So I am trying to figure out how I can remove a select set of characters on the end of a string. I've tried some general 'solutions' like str.replace or creating a rtrim, but I kept seeing some situation in which it wouldn't work.
Possible inputs might be:
\r\n some random text \r\n
\r\n some random text
some random text \r\n
some random text
Only the first and the third line should be affected by this function.
Basicly I'm looking for a rtrim function that takes as a parameter, the value/character set that should be trimmed.
I think it might be something way too obvious that I don't see, but at this point I feel like I could use some help.
You can use the following piece of code to do that for you:
var a = "\r\n some random text \r\n";
a = a.replace(new RegExp('\r\n$'), '');
Here, $ matches end of input.
You can refer to the regular expressions guide here to find out more about regex in JS.
EDIT:
If you really need a function for this:
var rTrimRegex = new RegExp('\r\n$');
var rTrim = function(input){
return input.replace(rTrimRegex, '');
}
And then use it inside your code maybe like:
var str = 'my name is foo\r\n\r\n';
str = rTrim(str);

How to replace string with the main string with javascript

Trying to do something like making html codes usable in my forum. I want to make text hidden when wrapped with the [hidden] string and after clicking on a button the original text between the [hidden] and [/hidden] tags should be shown. I try using
var res = str.replace("[hidden]$1[/hidden]", "$1");
You need to escape the brackets, [], otherwise they will be interpreted as a character set.
var string = '[hidden]test[/hidden]';
string = string.replace(/\[hidden\](.*?)\[\/hidden\]/g, '$1');
// "test"

regular expression not matching on javascript but matches on other languages

so I've been running around regexp for a while now, and been using RegEx101 to test my patterns, and it never failed (yet).
So I am trying to replace android Emojicons strings to their appropriate HTML image tage via regex, the code seems to match without an issue in the site above, and even works with PHP, but somehow, it doesn't match at all in javascript... so here is my code:
function loadEmojisInMessage(message) {
var regExp = /({emoji:(.*?)})/g; //var regExp = new RegExp("({emoji:(.*?)})","g");
message.replace(regExp, '<img src="emojis/emoji_$2.png" id="$2" class="emojicon" />').toString();
return message;
}
at first I thought I am doing something wrong, so I changed the code to this, just for testing
function loadEmojisInMessage(message) {
var regExp = /({emoji:(.*?)})/g; //var regExp = new RegExp("({emoji:(.*?)})","g");
message.replace(regExp, 'test?').toString();
return message;
}
but even this does not replace at all! (my thought is that it is having an issue matching the pattern in the string :/ )
example strings to match :
{emoji:em_1f50f}
What I am trying to do here is replace the entire string (above) with image HTML tag, while using the second match [it is the second bracket () ] for the URL string
Best Regards
UPDATE :
I forgot to add first matching bracket, sorry!
Also, you can test the pattern here
You're not assigning the result of the replace() method call back to the variable message. If you don't to this, message remains unchanged.
message = message.replace(regExp, '<img src="emojis/emoji_$2.png" id="$2" class="emojicon" />');

Removing non-break-spaces in JavaScript

I am having trouble removing spaces from a string. First I am converting the div to text(); to remove the tags (which works) and then I'm trying to remove the "&nbsp" part of the string, but it won't work. Any Idea what I'm doing wrong.
newStr = $('#myDiv').text();
newStr = newStr.replace(/ /g, '');
$('#myText').val(newStr);
<html>
<div id = "myDiv"><p>remove space</p></div>
<input type = "text" id = "myText" />
</html>
When you use the text function, you're not getting HTML, but text: the entities have been changed to spaces.
So simply replace spaces:
var str = " a     b   ", // bunch of NBSPs
newStr = str.replace(/\s/g,'');
console.log(newStr)
If you want to replace only the spaces coming from do the replacement before the conversion to text:
newStr = $($('#myDiv').html().replace(/ /g,'')).text();
.text()/textContent do not contain HTML entities (such as ), these are returned as literal characters. Here's a regular expression using the non-breaking space Unicode escape sequence:
var newStr = $('#myDiv').text().replace(/\u00A0/g, '');
$('#myText').val(newStr);
Demo
It is also possible to use a literal non-breaking space character instead of the escape sequence in the Regex, however I find the escape sequence more clear in this case. Nothing that a comment wouldn't solve, though.
It is also possible to use .html()/innerHTML to retrieve the HTML containing HTML entities, as in #Dystroy's answer.
Below is my original answer, where I've misinterpreted OP's use case. I'll leave it here in case anyone needs to remove from DOM elements' text content
[...] However, be aware that re-setting the .html()/innerHTML of an element means trashing out all of the listeners and data associated with it.
So here's a recursive solution that only alters the text content of text nodes, without reparsing HTML nor any side effects.
function removeNbsp($el) {
$el.contents().each(function() {
if (this.nodeType === 3) {
this.nodeValue = this.nodeValue.replace(/\u00A0/g, '');
} else {
removeNbsp( $(this) );
}
});
}
removeNbsp( $('#myDiv') );
Demo

How to replace particular string from a multiline textarea using jQuery?

When i have string which consists of a single line, replace works just fine.
As soon as i type in some text into text area and press enter as for new line, replace won't work anymore.
var currentValue = $('#service-field').val();
$('#service-field').val(currentValue.replace("particular string",""));
What should I do?
Try this to make sure you capture all occurrences, and not just the ones on the first line:
$('#service-field').val(currentValue.replace(/particular string/g, ""));
Or with a variable:
var t = "particular string";
$('#service-field').val(currentValue.replace(eval("/" + t + "/g"), ""));

Categories

Resources