Match #(\w+) and replace in javascript - javascript

I'm trying to match #(\w+) in a div content and remove it.
Here's what i've tried : http://jsfiddle.net/mxgde6m7/1/ .
#(\w+) works , but it doesn't replace with space.
var content = document.getElementById('contentbox');
var find = '#(\w+)';
var reg = new RegExp(find, 'g');
var result = content.innerHTML.replace(reg, ' ');
alert(result);
<div id="contentbox">#d test
What i want: <div id="contentbox">test
</div>
Thanks in advance.
EDIT
Okay, one problem solved, another one came up.
My script http://jsfiddle.net/mxgde6m7/9/ works perfectly there, but when i try it on my website, only a half works. The last part where it should replace #(\w+) with space doesn't work at all. If i copy/paste the CONTENT of the function in console(chrome), it works , but if i paste the function and i call it, it doesn't work.
Please help ! I'm stuck.

Using a RegExp constructor, you need two backslashes \\ in place of each backslash \.
var find = '#(\\w+)';

hwnd is correct that you need to double escape \w in your regular expression.
var find = '#(\\w+)';
But, you could also make this code much cleaner by defining a regex literal like so -
var content = document.getElementById('contentbox');
var result = content.innerHTML.replace(/#(\w+)/g, ' ');
alert(result);
Doing it this way doesn't require double escaping, as it's not a string.

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);

Is it possible to cut off the beginning of a string using regex?

I have a string which contains a path, such as
/foo/bar/baz/hello/world/bla.html
Now, I'd like to get everything from the second-last /, i.e. the result shall be
/world/bla.html
Is this possible using a regex? If so, how?
My current solution is to split the string into an array, and join its last two members again, but I'm sure that there is a better solution than this.
For example:
> '/foo/bar/baz/hello/world/bla.html'.replace(/.*(\/.*\/.*)/, "$1")
/world/bla.html
You can also do
str.split(/(?=\/)/g).slice(-2).join('')
> '/foo/bar/baz/hello/world/bla.html'.match(/(?:\/[^/]+){2}$/)[0]
"/world/bla.html"
Without regular expression:
> var s = '/foo/bar/baz/hello/world/bla.html';
> s.substr(s.lastIndexOf('/', s.lastIndexOf('/')-1))
"/world/bla.html"
I think this will work:
var str = "/foo/bar/baz/hello/world/bla.html";
alert( str.replace( /^.*?(\/[^/]*(?:\/[^/]*)?)$/, "$1") );
This will allow for there being possibly only one last part (like, "foo/bar").
You can use /(\/[^\/]*){2}$/ which selects a slash and some content twice followed by the end of the string.
See this regexplained.

jquery .replace(/./g, "") do not work for me but others

I found this snippet somewhere and it works like a charm:
var n = parseInt(e.find("span.favNum").text().replace(/./g, "")) + 1;
If I do it in a similar way it doesn't work anymore.
I do the following:
<div id ="test">6.987</div>
var test = $("#test");
var r = test.text().replace(/./g, "");
console.log("wrong ", r);
I know that I can replace it also like this:
var r = test.text().replace(".", "");
This works.
I would like to understand why the "stolen" snippet is working.
Any idea?
http://jsfiddle.net/nJZMf/3/
The original script is found here: http://wp-svbtle.themeskult.com/
You will find the snippet by viewing the source of index.html and searching for .replace.
You need to escape the "."
test.text().replace(/\./g, "");
The reason that the code in the page you linked to works, where yours doesn't, is that it's not the same regular expression. Here's what I found in that page (and similar code in several places)
r = n.text().replace( /,/g, "" )
where r is a jQuery object.
Note that the regular expression has a , inside the //, not a . like the code you had trouble with.
Comma is not a special character in regular expressions, so it needs no special treatment. Period has a special meaning. As the other answers pointed out, it matches all characters, and you need to prefix it with \ if you want to match . only.
Also note that .replace() is not jQuery code, it's JavaScript.
jQuery's .text() method returns a JavaScript String value. So anything you do with that string - such as the .replace() call - is actually a JavaScript String method.
The distinction is important when you want to research a problem: a search for "javascript string replace" will get you better information than "jquery replace".
It has to be var r = test.text().replace(/\./g, ""); instead of var r = test.text().replace(/./g, ""); because you need to escape the . in order for it to be replaced.
http://jsfiddle.net/mrk1989/nJZMf/4/
Solution because I add \ in var r = test.text().replace(/\./g, "");
The problem was that you did not escape dot.
But keep in mind that:
.replace(".", "");
.replace(/\./g, "");
are two different things.
For example: https://jsfiddle.net/rmhpkz9n/1/

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]);

pattern matchin using javascript doesnt wrk when special characters and numbers come in between

I am trying to create a pattern matching to find word contents in an article for my website.. I am unable to make the pattern matchings when a special character or a number comes in between the words, I will add the jsfiddle link.. also is it possible to find the number of occurences and add a button which on clicking go to each occurence one by one...This is the way my pgrm is currently wrking http://jsfiddle.net/ehzPQ/12/
I think the problem has to do with the boundaries you choose for your words, I believe that with \b you are not taking into account the case where the word is has a dot before (like ".cancer9". But I'm really not an expert in regex... so, I worked a little bit and got this solution, but I'm not sure if it will work for you:
Javascript:
$(document).ready(function () {
var $test = $('#article');
var entityText = $('#entity').html().replace(/\./g, "\\\.").replace(/\$/g, "\\\$").replace(/\?/g, "\\\?"); //etc...
var entityRegularExpression =new RegExp("([^a-zA-Z0-9])(" + entityText + ")([^a-zA-Z0-9])", "gi");
var highlight = '$1<span class="highlight">$2</span>$3';
$test.html($test.html().replace(entityRegularExpression, highlight));
});
And here you have a working demo: http://jsfiddle.net/ehzPQ/20/
Let me know if it works for you.

Categories

Resources