Variable in match (javascript) - javascript

<body class="reviews"></body>
var body = document.body;
var target = 'reviews';
if (body.className.match('/\b' + target + '\b/'))
console.log(true);
else
console.log(false);
This code returns false. But if I use body.className.match(/\breviews\b/) it returns true.
What's wrong with it?
I tried to escape a variable in a regex, no luck.

You are searching for the literal string '/\breviews\b/', it's not being read as a RegEx.
You need to use the new RegExp method.
body.className.match(new RegExp('\\b' + target + '\\b'))
Note: Don't use delimiters with new RegExp. Also, note that \\b has 2 \.

Related

replace \r\n with < br /> as text

Trying for 2 hours to replace \r\n with < br/> but it seems to be impossible.
I don't know what i'm doing! Please help!
const text = '"Hello!\r\n\r\nThis is a dog!'
const checkText = str=> {
const match = /\r|\n/.exec(text);
if (match) {
//return str.replace(/(?:\\[rn]|[\r\n]+)+/g, '<br/>');
return str.replace('/r/n', '<br/>');
}
return str;
};
checkText(text)
Just do this:
text.replace(/\r\n/g, '<br/>');
Covering all the possible new line character combinations.
String tmp = s.replaceAll("\r\n", "<br>"); // Windows
tmp = tmp.replaceAll("\r", "<br>"); // Old MAC
return tmp.replaceAll("\n", "<br>"); // Linux / UNIX
You may try:
(text+ '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1<br/>$2');
There are multiple things wrong with your code:
String.prototype.replace only replaces the first occurrence of a string. You need to use a regex argument with the /g flag to replace all occurrences.
Escapes use a backslash, not a forward slash: Use \r\n, not /r/n.
checkText returns a string, but your call-site doesn't do anything with the returned string - it's just dropped. Strings are immutable in JavaScript.
I don't recommend using strings to hold HTML because it can (very easily) cause HTML-injection (including <script>-injection) attacks.
Instead, do one of the following:
Use String.prototype.split and HTML-encode each string in the array and join with "<br />".
Add the string directly to the document with .textContent (don't use innerText anymore) and give the parent element the CSS style whitespace: pre-wrap;.

Javascript str.replace with variables

I have found a short script which finds a line with a certain phrase in it and replaces the whole line with a new line. However I can't work out how to include a variable where it says '#RemoveMe' in the str.replace. (I want to include the variable 'start' which is passed in by the function's trigger, to make --> (/^.start.$/mg, ""))
Any help appreciated...
var str = 'line1\n'+
'line2\n'+
'#RemoveMe line3\n'+
'line4';
var test = str.replace(/^.*#RemoveMe.*$/mg, "");
Thanks.
This is a limitation of the inline regular expression notation.
If you use new RegExp() you can pass the expression as a string.
var find = "start";
var regexp = new RegExp("^.*" + find + ".*$", "mg"); // note: no delimiters
str.replace(regexp, "");

JavaScript does not replace the last symbol of the string

I have try to replace a symbol in JavaScript, but somehow this is always only replace the 1st symbol of the string instead of replaced all the symbol.
JavaScript:
var note = "test'test'test'";
note = note .replace("'", "'");
Output:
test'test'test'
Does anyone know how can I can replace all ' symbols with ' ??
Use regex substitution and add a g flag to make it global:
> "test'test'test'".replace(/'/g, ''');
"test'test'test'"
Use g suffix for the Global substituation.
This is the right way:
note = "test'test'test'";
note.replace(/\'/g,"'")
Check this: jsfiddle
Try this note.replace(/\'/g, ''');

Javascript RegExp help

I am trying to replace a certain text in Javascript.
newexp is a variable.
numexp is a variable
replacenamestring = new RegExp('Memberresumeexp\[1\]',"ig");
newexp = newexp.replace(replacenamestring,'Memberresumeexp[' + numexp + ']');
The above replace is not working.
How ever this works.
newexp = newexp.replace(/Memberresumeexp\[1\]/ig,'Memberresumeexp[' + numexp + ']');
Not able to figure out why?
Your first line creates a Javascript string, then parses the string as a regex.
Javascript string literals use \ as an escape character, so the \s are not part of the string value. Therefore, the [ and ] in your regex aren't escaped, so it's creating a character class.
You need to escape the \s by writing \\.
Here's a working example for you with one BIG caveat -- I changed "[1]" to "[\d+]" just in case you needed this for more cases of Memberresumeexp[<any number>]. Also, I hardcoded numexp, because I had not seen how it was initialized.
var replacenamestring = new RegExp('Memberresumeexp\\[\\d+\\]',"ig");
var newexp = "asdfasdflkj;lakwjef Memberresumeexp[1] asdfasdfasdf\nqwerqwerwer Memberresumeexp[2] qwerqwerwqerewr\n";
var numexp = 123;
if(replacenamestring.test(newexp))
{
newexp = newexp.replace(replacenamestring,'Memberresumeexp[' + numexp + ']');
}
It's a simple lexical syntax issue. In the first case, you're creating the RegExp object with the constructor, which starts from a string constant. Well, string constants have their own syntactic quirks, and in particular those backslashes in the string will be interpreted during its own parsing. By the time the RegExp constructor is called, those are gone.
The "native" RegExp syntax has its own quoting rules, which are such that the "[" and "]" portions of the pattern are correctly interpreted when you use that syntax.

How to replace multiple strings with replace() in Javascript

I'm guessing this is a simple problem, but I'm just learning...
I have this:
var location = (jQuery.url.attr("host"))+(jQuery.url.attr("path"));
locationClean = location.replace('/',' ');
locationArray = locationClean.split(" ");
console.log(location);
console.log(locationClean);
console.log(locationArray);
And here is what I am getting in Firebug:
stormink.net/discussed/the-ideas-behind-my-redesign
stormink.net discussed/the-ideas-behind-my-redesign
["stormink.net", "discussed/the-ideas-behind-my-redesign"]
So for some reason, the replace is only happening once? Do I need to use Regex instead with "/g" to make it repeat? And if so, how would I specifiy a '/' in Regex? (I understand very little of how to use Regex).
Thanks all.
Use a pattern instead of a string, which you can use with the "global" modifier
locationClean = location.replace(/\//g,' ');
The replace method only replaces the first occurance when you use a string as the first parameter. You have to use a regular expression to replace all occurances:
locationClean = location.replace(/\//g,' ');
(As the slash characters are used to delimit the regular expression literal, you need to escape the slash inside the excpression with a backslash.)
Still, why are you not just splitting on the '/' character instead?
You could directly split using the / character as the separator:
var loc = location.host + location.pathname, // loc variable used for tesing
locationArray = loc.split("/");
This can be fixed from your javascript.
SYNTAX
stringObject.replace(findstring,newstring)
findstring: Required. Specifies a string value to find. To perform a global search add a 'g' flag to this parameter and to perform a case-insensitive search add an 'i' flag.
newstring: Required. Specifies the string to replace the found value from findstring
Here's what ur code shud look like:
locationClean = location.replace(new RegExp('/','g'),' ');
locationArray = locationClean.split(" ");
njoi'

Categories

Resources