Is it possible, using jQuery (Or anything else), to remove certain bits of text from an element but leave the rest intact?
I'm using a Wordpress plugin that compiles all my tweets into WP posts but the post titles are automatically saved using the full text body of the tweet. For example;
#username http://t.co/XXXXXXXX #hashtag
I want to be able to remove the hyperlink and also the #hashtag
The hashtag will always be the same (Ie; it will always be #hashtag), but the hyperlink will change with every post. Is there a way that I can do this?
Things could be harder or easier depending on whether the username, link and hashtag are always in the same position of the tweet or not. But I might suggest splitting the tweet string on ' ' and looping to construct a string without words that begin with '#', 'http://t.co', and '#'.
It would be easier with a full example because you may not want to remove all the handles, usernames, and hashtags. But I do suspect there is some uniformity in the format you may want to exploit.
Example:
var words = $(el).text().split(' ');
var cleaned = [];
for (var i = 0, len = words.length; i < len; i++) {
if (!(words[i].indexOf('#') === 1)) { // ... etc for other characters
cleaned.push(words[i]);
}
}
var cleaned_string = cleaned.join(' ');
You can use regular expressions to remove the url and the hastags, for example:
To remove the http part:
fullTweet.replace(/http:\/\/.+?\s/g, "");
The regular expression means http:// followed by any number of characters until a space (use non-eager, i.e. +?, meaning it will stop at the first space)
To remove the hashtag
fullTweet.replace(/#.+?(\s|$)/g, "");
Here it's a # followed by any character until a space or end of string
Here's a complete example.
Good reference for javascript regular expressions.
Jquery Link:
var test = "#username http://t.co/XXXXXXXX #hashtag";
var matchindex = test.indexOf("#");
alert(matchindex); // Tells you at what index the hashtag starts
var res = test.split("#");
alert(res[0]); // Gives you rest of the string without hastag
You can do something like this, to get the string without hashtag.You'll have to get the whole text as string into a variable first.
Related
I'm implementing a mentions mechanism in a React based chat application. When the user types # in the textarea I am opening a list of members of the group and performing a search in that list using the text which comes after the # char. The code for search query extraction is as follows:
const regexp = /#(\S+)/g;
const text = regexp.exec(message);
let mentionText = '';
mentionText = text ? text[0] : '#';
This works only if there's 1 # char in the string. For example, if there's an e-mail written in the message text before the # char which opens the list of members, this will not work because I'm taking the first item in the array which is the e-mail.
Is there a better/more elegant/better working way to get the search term from the entered string? I basically need to take the text which comes after # char which is not an e-mail, for example. Yes, to be more precise - text before # char which has a heading space. That way I can tell for sure that the user wants to write a mention. Basically I think it should be like this #. If there's a space and a # sign next to it - the user is writing a mention. The problem is how to identify that # - with a heading space.
Thanks!
RegEx has an internal parameter which stores the last match index so that when you run it the next time, you get the next match. Just keep running the regex in a while loop.
const message = "#player with player#email went to #place."
const regexp = /#(\S+)/g;
const mentions = [];
let text;
while (text = regexp.exec(message)) {
let mentionText = '';
mentionText = text ? text[1] : '#';
mentions.push(mentionText)
}
console.log("mentions", mentions)
At the start of the regular expression, alternate between a space and the start of the string. Then lose the global flag (you're only looking for one match, after all). Use optional chaining to keep things concise.
const mentionText = /(?: |^)#(\S+)/.exec(message)?.[1] ?? '#';
I have the following example url: #/reports/12/expense/11.
I need to get the id just after the reports -> 12. What I am asking here is the most suitable way to do this. I can search for reports in the url and get the content just after that ... but what if in some moment I decide to change the url, I will have to change my algorythm.
What do You think is the best way here. Some code examples will be also very helpfull.
It's hard to write code that is future-proof since it's hard to predict the crazy things we might do in the future!
However, if we assume that the id will always be the string of consecutive digits in the URL then you could simply look for that:
function getReportId(url) {
var match = url.match(/\d+/);
return (match) ? Number(match[0]) : null;
}
getReportId('#/reports/12/expense/11'); // => 12
getReportId('/some/new/url/report/12'); // => 12
You should use a regular expression to find the number inside the string. Passing the regular expression to the string's .match() method will return an array containing the matches based on the regular expression. In this case, the item of the returned array that you're interested in will be at the index of 1, assuming that the number will always be after reports/:
var text = "#/reports/12/expense/11";
var id = text.match(/reports\/(\d+)/);
alert(id[1]);
\d+ here means that you're looking for at least one number followed by zero to an infinite amount of numbers.
var text = "#/reports/12/expense/11";
var id = text.match("#/[a-zA-Z]*/([0-9]*)/[a-zA-Z]*/")
console.log(id[1])
Regex explanation:
#/ matches the characters #/ literally
[a-zA-Z]* - matches a word
/ matches the character / literally
1st Capturing group - ([0-9]*) - this matches a number.
[a-zA-Z]* - matches a word
/ matches the character / literally
Regular expressions can be tricky (add expensive). So usually if you can efficiently do the same thing without them you should. Looking at your URL format you would probably want to put at least a few constraints on it otherwise the problem will be very complex. For instance, you probably want to assume the value will always appear directly after the key so in your sample report=12 and expense=11, but report and expense could be switched (ex. expense/11/report/12) and you would get the same result.
I would just use string split:
var parts = url.split("/");
for(var i = 0; i < parts.length; i++) {
if(parts[i] === "report"){
this.reportValue = parts[i+1];
i+=2;
}
if(parts[i] === "expense"){
this.expenseValue = parts[i+1];
i+=2;
}
}
So this way your key/value parts can appear anywhere in the array
Note: you will also want to check that i+1 is in the range of the parts array. But that would just make this sample code ugly and it is pretty easy to add in. Depending on what values you are expecting (or not expecting) you might also want to check that values are numbers using isNaN
I am pulling content from an RSS feed, before using jquery to format and edit the rss feed (string) that is returned. I am using replace to replace strings and characters like so:
var spanish = $("#wod a").text();
var newspan = spanish.replace("=","-");
$("#wod a").text(newspan);
This works great. I am also trying to remove all text after a certain point. Similar to truncation, I would like to hide all text starting from the word "Example".
In this particular RSS feed, the word example is in every feed. I would like to hide "example" and all text the follows that word. How can I accomplish this?
Though there is not enough jQuery, you even don't need it to remove everything after a certain word in the given string. The first approach is to use substring:
var new_str = str.substring(0, str.indexOf("Example"));
The second is a trick with split:
var new_str = str.split("Example")[0];
If you also want to keep "Example" and just remove everything after that particular word, you can do:
var str = "aaaa1111?bbb&222:Example=123456",
newStr = str.substring(0, str.indexOf('Example') + 'Example'.length);
// will output: aaaa1111?bbb&222:Example
jQuery isn't intended for string manipulation, you should use Vanilla JS for that:
newspan = newspan.replace(/example.*$/i, "");
The .replace() method accepts a regular expression, so in this case I've used /example.*$/i which does a case-insensitive match against the word "example" followed by zero or more of any other characters to the end of the string and replaces them with an empty string.
I would like to hide all text starting from the word "Example"
A solution that uses the simpler replace WITH backreferences so as to "hide" everything starting with the word Example but keeping the stuff before it.
var str = "my house example is bad"
str.replace(/(.*?) example.*/i, "$1") // returns "my house"
// case insensitive. also note the space before example because you
// probably want to throw that out.
I am writing a little app for Sharepoint. I am trying to extract some text from the middle of a field that is returned:
var ows_MetaInfo="1;#Subject:SW|NameOfADocument
vti_parservers:SR|23.0.0.6421
ContentTypeID:SW|0x0101001DB26Cf25E4F31488B7333256A77D2CA
vti_cachedtitle:SR|NameOfADocument
vti_title:SR|ATitleOfADocument
_Author:SW:|TheNameOfOurCompany
_Category:SW|
ContentType:SW|Document
vti_author::SR|mrwienerdog
_Comments:SW|This is very much the string I need extracted
vti_categories:VW|
vtiapprovallevel:SR|
vti_modifiedby:SR|mrwienerdog
vti_assignedto:SR|
Keywords:SW|Project Name
ContentType _Comments"
So......All I want returned is "This is very much the string I need extracted"
Do I need a regex and a string replace? How would you write the regex?
Yes, you can use a regular expression for this (this is the sort of thing they are good for). Assuming you always want the string after the pipe (|) on the line starting with "_Comments:SW|", here's how you can extract it:
var matchresult = ows_MetaInfo.match(/^_Comments:SW\|(.*)$/m);
var comment = (matchresult==null) ? "" : matchresult[1];
Note that the .match() method of the String object returns an array. The first (index 0) element will be the entire match (here, we the entire match is the whole line, as we anchored it with ^ and $; note that adding the "m" after the regex makes this a multiline regex, allowing us to match the start and end of any line within the multi-line input), and the rest of the array are the submatches that we capture using parenthesis. Above we've captured the part of the line that you want, so that will present in the second item in the array (index 1).
If there is no match ("_Comments:SW|" doesnt appear in ows_MetaInfo), then .match() will return null, which is why we test it before pulling out the comment.
If you need to adjust the regex for other scenarios, have a look at the Regex docs on Mozilla Dev Network: https://developer.mozilla.org/en/JavaScript/Guide/Regular_Expressions
You can use this code:
var match = ows_MetaInfo.match(/_Comments:SW\|([^\n]+)/);
if (match)
document.writeln(match[1]);
I'm far from competent with RegEx, so here is my RegEx-less solution. See comments for further detail.
var extractedText = ExtractText(ows_MetaInfo);
function ExtractText(arg) {
// Use the pipe delimiter to turn the string into an array
var aryValues = ows_MetaInfo.split("|");
// Find the portion of the array that contains "vti_categories:VW"
for (var i = 0; i < aryValues.length; i++) {
if (aryValues[i].search("vti_categories:VW") != -1)
return aryValues[i].replace("vti_categories:VW", "");
}
return null;
}
Here's a working fiddle to demonstrate.
I have a URL that can be divided in 3 parts and I want the middle one.
The URL is like this
http://www.site.com/place?siteurl=http://www.thisIsWhatIwant.com/bla/bla/&XXX
XXX means that the URL continues and may have a lot of characters including %, parenthesis, other ampersands, equal signs, etc...
I want what is in bold. I other words, to get rid of everything that is before the equal sign on siteurl= (including the equal sign) and also get rid of everything that is after the first ampersand after that, including the ampersand... so, after cleaning the URL it would become just:
http://www.thisIsWhatIwant.com/bla/bla/
how do I do that with Javascript's str.replace()?
thanks in advance
Rather than remove the text you don't want, you can extract the text you do want using String.match():
var s = "http://www.site.com/place?siteurl=http://www.thisIsWhatIwant.com/bla/bla/&XXX";
var middle = s.match(/siteurl\=(.*?)\&/i)[1];
You don't want to use String.replace here, use String.split:
if(window.location.search.indexOf('siteurl') > -1) {
var siteurl = window.location.search.split('siteurl=')[1];
siteurl = siteurl.substring(0, siteurl.indexOf('&'));
//do something with siteurl...
} else {
//siteurl is not in the URL.
}