Replace a period with HTML character - javascript

I am having a problem with some code. I put in an input and text in a paragraph is highlighted using <mark>. But when I add a period to highlight all the periods, the code freaks out and gives me the actual html code and has random highlights. So I tried to add a replacer to change the periods. Now it won't freak out but with won't highlight anything. Here is my code to try to replace the period with the html character number (.):
var i = document.getElementById("Bar").value;
var inpu = $.trim(i);
var inp = inpu.replace(".", ".");
var SearchReq = new RegExp("(\\b" + inp + "\\b)", "gim");
var Notes = document.getElementById("NoteHolder").innerHTML;
var after = Notes.replace(SearchReq, "<mark class=" + ColorOptionReady + ">$1</mark>");
document.getElementById("NoteHolder").innerHTML = after;
What is the problem with the code? (I tried removing the "\b" in the regex but that didn't fix it.)

Replace . to \\. ( escape it, \\ backslash required to keep backslash when you would pass string to RegExp) :
var inp = inpu.replace(".", "\\.");
Reason of your error is that . is character which has special meaning in RegExp, so you have to escape it prior passing to RefExp.
See Special characters meaning in regular expressions for more information.
Good Luck )!

Related

decimal emoji with using regex

I want to change my keyboard character with sad emoji using html decimal code and javascript regex. I just want to conflate that two characters ':' and '('
How can I write that emojiSmile regex variable?
Here are my code below.
var finalAnswer = ':)';
var emojiSmile = /\:+[)]/g;
var emojiSmileDecimal = '😊';
if (finalAnswer.match(emojiSmile)) {
var emojies = finalAnswer.replace(emojiSmile, emojiSmileDecimal);
}
It already works as you wrote it.
From first principles, you just need to escape the ) as \) because it's a special character in regex syntax:
var emojiSmile = /:\)/g;
Escaping it with brackets ([)]), like you did, also works:
var emojiSmile = /:[)]/g;
There is no need to escape : or to put a + behind it (unless you want to match ::::) as well).

ASCII character not being recognized in if statement

I am trying to get a string from a html page with jquery and this is what I have.
var text = $(this).text();
var key = text.substring(0,1);
if(key == ' ' || key == 'Β ')
key = text.substring(1,2);
text is this Β Home
And I want to skip the space and or the keycode above It appears this code does not work either. It only gets the text.substring(0,1); instead of text.substring(1,2); because the if statement is not catching.= and I am not sure why. Any help would be super awesome! Thanks!
There are several problems with the code in the question. First, Β  has no special meaning in JavaScript: it is a string literal with six characters. Second, text.substring(1,2) returns simply the second character of text, not all characters from the second one onwards.
Assuming that you wish to remove one leading SPACE or NO-BREAK SPACE (which is what Β  means in HTML; it is not an Ascii character, by the way), then the following code would work:
var first = text.substring(0, 1);
if(first === ' ' || first === '\u00A0') {
text = text.substring(1, text.length);
}
The notation \u00A0 is a JavaScript escape notation for NO-BREAK SPACE U+00A0.
Should you wish to remove multiple spaces at the start, and perhaps at the end too, some modifications are needed. In that case, using a replace operation with regular expression is probably best.
If you want remove spaces at the beginning (and end) of a string, you can use the trim function
var myvar = " home"
myVar.trim() // --> "home"
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim

Regex replace text outside html tag

I'm working on an autocomplete component that highlights all ocurrences of searched text. What I do is explode the input text by words, and wrap every ocurrence of those words into a
My code looks like this
inputText = 'marriott st';
text = "Marriott east side";
textSearch = inputText.split(' ');
for (var i in textSearch) {
var regexSearch = new RegExp('(?!<\/?strong>)' + textSearch[i]), "i");
var textReplaced = regexSearch.exec(text);
text = text.replace(regexSearch, '< strong>' + textReplaced + '< /strong>');
}
For example, given the result: "marriott east side"
And the input text: "marriott st"
I should get
<strong>marriot< /strong > ea < strong >st < /strong > side
And i'm getting
<<strong>st</strong>rong>marriot</<strong>st </strong>rong>ea<<strong>st</strong> rong>s</strong> side
Any ideas how can I improve my regex, in order to avoid ocurrences inside the html tags? Thanks
/(?!<\/?strong>)st/
I would process the string in one pass. You can create one regular expression out of the search string:
var search_pattern = '(' + inputText.replace(/\s+/g, '|') + ')';
// `search_pattern` is now `(marriot|st)`
text = text.replace(RegExp(search_pattern, 'gi'), '<strong>$1</strong>');
DEMO
You could even split the search string first, sort the words by length and combine them, to give a higher precedence to longer matches.
You definitely should escape special regex characters inside the string: How to escape regular expression special characters using javascript?.
Before each search, I suggest getting (or saving) the original search string to work on each time. For example, in your current case that means you could replace all '<strong>' and '</strong>' tags with ''. This will help keep your regEx simple, especially if you decide to add other html tags and formatting in the future.

Regex that only works on browser tester

I've tested my regex on Regex testers and it worked, but I didn't get it to work on my code.
var mail = "chdelfosse#gmail.com";
var regExp = new RegExp("#(.*?)\.");
document.write(regExp.exec(mail)) ;
I get this result :
#g,
I tried to add a backslash before the dot, and I got this :
#gmail.,gmail
I also wanted to remove the "#" and the "." from the email, so I tried to use " (?:#) ", but I didn't get it to work (on Regex testers).
It's my first time trying to use Regex, and I don't get it.
Why is there a comma ?
You can use this regex to get the domain name:
/#(.+)\./
Live DEMO
Faster than regex:
var emailAddress = "my.email#gmail.com";
var array_email = emailAddress.split("#");​​
alert('Account: ' + array_email[0] +'; Domain: ' + array_email[1]);​​​​​​​​​​​​​​​​​​​​​​​​​​
A couple things to do differently:
You need to double escape your backslash in the string so that one backslash still remains for the RegExp constructor or switch to the /regex here/ syntax.
If you want just the subgroup in the parens, you need to refer to that specific subgroup.
Here's the code:
var mail = "chdelfosse#gmail.com";
console.log(mail.match(/#(.*?)\./)[1]);

How to replace whitespaces using javascript?

I'm trying to remove the whitespaces from a textarea . The below code is not appending the text i'm selecting from two dropdowns. Can somebody tell me where i'd gone wrong? I'm trying to remove multiple spaces within the string as well, will that work with the same? Dont know regular expressions much. Please help.
function addToExpressionPreview() {
var reqColumnName = $('#ddlColumnNames')[0].value;
var reqOperator = $('#ddOperator')[0].value;
var expressionTextArea = document.getElementById("expressionPreview");
var txt = document.createTextNode(reqColumnName + reqOperator.toString());
if (expressionTextArea.value.match(/^\s+$/) != null)
{
expressionTextArea.value = (expressionTextArea.value.replace(/^\W+/, '')).replace(/\W+$/, '');
}
expressionTextArea.appendChild(txt);
}
> function addToExpressionPreview() {
> var reqColumnName = $('#ddlColumnNames')[0].value;
> var reqOperator = $('#ddOperator')[0].value;
You might as well use document.getElementById() for each of the above.
> var expressionTextArea = document.getElementById("expressionPreview");
> var txt = document.createTextNode(reqColumnName + reqOperator.toString());
reqOperator is already a string, and in any case, the use of the + operator will coerce it to String unless all expressions or identifiers involved are Numbers.
> if (expressionTextArea.value.match(/^\s+$/) != null) {
There is no need for match here. I seems like you are trying to see if the value is all whitespace, so you can use:
if (/^\s*$/.test(expressionTextArea.value)) {
// value is empty or all whitespace
Since you re-use expressionTextArea.value several times, it would be much more convenient to store it an a variable, preferably with a short name.
> expressionTextArea.value = (expressionTextArea.value.replace(/^\W+/,
> '')).replace(/\W+$/, '');
That will replace one or more non-word characters at the end of the string with nothing. If you want to replace multiple white space characters anywhere in the string with one, then (note wrapping for posting here):
expressionTextArea.value = expressionTextArea.value.
replace(/^\s+/,'').
replace(/\s+$/, '').
replace(/\s+/g,' ');
Note that \s does not match the same range of 'whitespace' characters in all browsers. However, for simple use for form element values it is probably sufficient.
Whitespace is matched by \s, so
expressionTextArea.value.replace(/\s/g, "");
should do the trick for you.
In your sample, ^\W+ will only match leading characters that are not a word character, and ^\s+$ will only match if the entire string is whitespace. To do a global replace(not just the first match) you need to use the g modifier.
Refer this link, you can get some idea. Try .replace(/ /g,"UrReplacement");
Edit: or .split(' ').join('UrReplacement') if you have an aversion to REs

Categories

Resources