Why the Ternary Operator isn't working right? - javascript

Well, I'm working in a Chat Room Website... and I have this Problem... For a reason the Ternary Operator doesn't give me the right output...
That's the Code Piece of code that does the Job...
html = html.replace(/(#[a-zA-Z0-9]{1,})/, "<span class='" + (myUsername == "$1".replace('#', '') ? "highlighted-username" : "") + "'>$1</span>");
Let's say That my name is "jimisdam" and someone writes in the Chat "#jimisdam"... So... I'm getting the $1 and removing the '#' to compare it with the myUsername(which is "jimisdam")
WHAT'S WRONG ??

JS doesn't know that you want it to substitute $1 into place before doing the replacement. It sees a method call to html.replace which takes 2 arguments:
the regex to match
the string to replace with
To calculate the second parameter, it evaluates this expression:
"<span class='" + (myUsername == "$1".replace('#', '') ? "highlighted-username" : "") + "'>$1</span>"
Note that $1 doesn't mean anything special here, because we're still deciding what string to pass into the replacement function. So:
"$1".replace('#', '') just results in "$1"
so unless your username happens to be $1, the comparison will always be false
so an empty string will be added to the class attribute
so the argument passed will always be "<span class=''>$1</span>"
Only now does replace get to see the remaining instance of $1 and substitute in the captured value.
One way to achieve what you're trying to do is to pass in a function rather than a string as the second parameter. That way, you get the matched sections of string as variables, and can use them to calculate the replacement.
Untested example, because I'm on a phone:
html = html.replace(/(#[a-zA-Z0-9]{1,})/, function(match) { return "<span class='" + (myUsername == match.replace('#', '') ? "highlighted-username" : "") + "'>" + match + "</span>"; })

Your “$1” string literal does not hold a submatch. That’s wrong.
However, the replace() method also takes a function as second argument. Try this:
html = html.replace(/(#[a-zA-Z0-9]{1,})/,function(){
return '<span class="' +
(myUsername == arguments[0].replace('#','') ? 'highlighted-username' : '')
+ '">' + arguments[0] + '</span>';
});

Related

JavaScript's console.log printing unwanted characters

So basically what I'm trying to do is print a simple string to the screen using the console.log function.
Here's an example :
const fromLabel: string = '["' + "AppExp" + '"]' + '\n' + '["' + "AppExp" + '"]';
And I ultimately wanna print it, so I go:
console.log(fromLabel);
and my output is:
[\"AppExp\"]\n[\"AppExp\"]
So, basically no carriage return and unwanted '\'.
Any idea what could be the problem?
EDIT: Never mind. I was working with objects and to print them I used JSON.stringify.. little did I know I used it on this string as well ..my bad
Backslashes are escaping certain characters in the string. Your string is put together in a weird way—you're mixing "" and ''. Try this:
var str = '["' + 'AppExp' + '"]' + '\n' + '["' + 'AppExp' + '"]'
console.log(str)
try this code with template literals
I omitted the : string to be able to run the snippet but remember to add it!
const fromLabel = `[""AppExp""]
[""AppExp""]`;
console.log(fromLabel);
or in case you do not want duplicate " chars
const fromLabel: string = `["AppExp"]
["AppExp"]`;
I hope it helps! :)

Javascript Regex: exclude result if preceded by href="

I'm struggling to get a string replaced in Javascript by a regex matching pattern.
I want to replace all matches of {{$myparam}} to be surrounded by a span tag.
This works (see code below). But I want to prevent replacements when a match is preceded by href=".
Example: href="{{$myparam}} must NOT be replaced.
{{$myparam}} MUST be replaced.
myparam can be any text string.
var highlighted = html.replace(/(\{\{(.*?)\}\})/g, function highlight(x) {
return "<span class='highlight'>" + x + "</span>";
});
I've checked out numerous examples in other threads, but I cannot find a solution that works for my case.
You could use
var subject = 'href="{{$myparam}}" or any other {{$myparam}}';
var regex = /"[^"]*"|(\{\{(.*?)\}\})/g;
replaced = subject.replace(regex, function(m, group1) {
if (typeof group1 == 'undefined') return m;
else return "<span class='highlight'>" + group1 + "</span>";
});
alert(replaced);
# href="{{$myparam}}" or any other <span class='highlight'>{{$myparam}}</span>
See a demo on regex101.com.
The idea here is to check for
not_interesting|not_interesting_either|(very_interesting)
and check for the presence of a captured group. You can put anything not interesting to the left as in this example: "[^"]*" (that is anything between double quotes).
If you want to read more on the subject, have a look here.
This seems a bit simpler, just make the href part optional:
mystring = 'this has {{$param1}} and {{$param2}} and href="{{$param3}}" too';
console.log(mystring
.replace(/(href=.)?\{\{([^{} ]+)\}\}/g,
function (match,chk,param) {
return "undefined" !== typeof(chk)
? match
: '<span class="highlight">' + param + '</span>';
}));
The second argument to the callback function is the 'check' part, and the third argument is the captured parameter name. Since the check part is optional and it's fairly precise, it'll only be defined at all if it's 'href="'.
Output, with newlines added for readability:
this has <span class="highlight">$param1</span>
and <span class="highlight">$param2</span>
and href="{{$param3}}" too

Regular expression to find and replace specific value from a URL

I am trying to extract ?ref value from a URL and wanted to replace it with some other value.
Example Lets say my URL is something like this http://myexample.com/?ref=test?nref=xml&page=1 or it can be http://myexample.com/?fref=like?ref=test?nref=xml&page=1
From the above url I wanted to find ?ref value and wanted to replace it from another string say "testing". Any help and also wanted to learn advance Regular expressions any help.
Thanks in advance.
A solution for your posted examples.
str = str.replace(/\b(ref=)[^&?]*/i, '$1testing');
Regular expression:
\b the boundary between a word char (\w) and and not a word char
( group and capture to \1:
ref= 'ref='
) end of \1
[^&?]* any character except: '&', '?' (0 or more times)
The i modifier is used for case-insensitive matching.
See working demo
Make sure you don't have two "?" in url. I assume you mean
http://myexample.com?ref=test&nref=xml&page=1
you can use the function below
here url is your url, name is the key, in your case it is "ref", and the new_value is the new value, i.e. the value that would replace "test"
the function will return the new url
function replaceURLParam (url, name, new_value) {
// ? or &, name=, anything that is not &, zero or more times
var str_exp = "[\?&]" + name + "=[^&]{0,}";
var reExp = new RegExp (str_exp, "");
if (reExp.exec (url) == null) { // parameter not found
var q_or_a = (url.indexOf ("?") == -1) ? "?" : "&"; // ? or &, if url has ?, use &
return url + q_or_a + name + "=" + new_value;
}
var found_string = reExp.exec (url) [0];
// found_string.substring (0, 1) is ? or &
return url.replace (reExp, found_string.substring (0, 1) + name + "=" + new_value);
}
Try this :
var name = 'ref',
value = 'testing',
url;
url = location.href.replace(
new RegExp('(\\?|&)(' + name + '=)[^&]*'),
'$1$2' + value
);
new RegExp('(\\?|&)(' + name + '=)[^&]*') gives /(\?|&)(ref=)[^&]*/ which means :
"?" or "&" then "ref=" then "everything but '&' zero or more times".
Finally, $1 holds the result of (\?|&) while $2 holds the result of (ref=).
Links to read : replace, regexp.

javascript search string contains ' + '

i would to search a string into another string but i'm facing an issue.
There is my code :
reference = "project/+bug/1234";
str = "+bug/1234";
alert(reference.search(str));
//it should alert 8 (index of matched strings)
but it alert -1 : so, str wasn't found into reference.
I've found what's the problem is, and it seems to be the " + " character into str, because .search("string+str") seems to evaluate searched string with the regex " + "
Just use string.indexOf(). It takes a literal string instead of converting the string to a RegExp object (like string.search() does):
> reference = "project/+bug/1234";
> str = "+bug/1234";
> console.log(reference.indexOf(str));
8
Try this:
reference = "project/+bug/1234";
str = "+bug/1234";
alert(reference.indexOf("+bug/1234"));

replace space with dash JavaScript

var html = "<div>"+title+"<br/>";
document.write(title.replace(/ /g,"-"));
html+= '<p><a href="go.aspx?title=' + title + '">Details<\/a></p></div>';
I want to replace title space with dash.
Try title.replace(/\s/g , "-") instead. (/\s/ is the regex escape for whitespace).
Also, do:
title = title.replace(/\s/g , "-");
var html = "<div>" + title + "</div>";
// ...
I find regex expressions commonly used in the replace function very hard to read - plus it's easy to forget to not quote the string you are searching for or to omit the /g to indicate a global replace. For doing something simple like replacing a space with a dash, using an easier to understand "split" followed by a "join" is just as fast.
alert("this is a test".split(" ").join("-"));
https://jsfiddle.net/n0u3aw5c/
Calling title.replace will not change title, but return a string where the values have been replaced. You need to use the returned value:
var html = "<div>"+title+"<br/>";
var newTitle = document.write(title.replace(/ /g,"-"));
html+= '<p><a href="go.aspx?title=' + newTitle + '">Details<\/a></p></div>';
The regular expression is fine, but will only replace spaces and not all whitespace.
var str = "Tatwerat Development Team";
str = str.replace(/\s+/g, '-');
document.write(str)
ehdv's answer gets you 90% of the way there. I just wanted to clarify where the code he suggested would go within your code, and it wouldn't look right in a comment.
var html = "<div>" + title + "<br/>";
title = title.replace(/\s/g , "-");
html+= '<p><a href="go.aspx?title=' + title + '">Details<\/a></p></div>';
This assumes that you DON'T want dashes in the div, but you DO in the URL.
And if you also want to replace multiple spaces that come immediately one after another with a SINGLE dash instead of ending up with double dashes in your title, use this instead:
var html = "<div>" + title + "<br/>";
title = title.replace(/\s+/g , "-");
html+= '<p><a href="go.aspx?title=' + title + '">Details<\/a></p>
I'd also like to mention that you're not closing your div. Maybe you just didn't include that part of your code but it's worth mentioning. There's also an unnecessary \ in your string. It's not hurting anything, but it's not needed. Maybe your code is meant to look like this:
var html = "<div>" + title + "</div>";
title = title.replace(/\s/g , "-");
html+= '<p>Details</p>

Categories