I'm making an extension for google chrome and i would like to be able find certain pieces of text and replace them with random letters or numbers using javascript except the certain text is a variable entered by the user for example they enter the word dog and all words that say dog are found and replaced as explained before . HELP greatly wanted
Try using the .replace() method of JavaScript.
Supposing you have a div like so for containing text: <div id="test">Original Text</div>, use this JavaScript code:
var orignalstring = document.getElementById("test").innerHTML;
var newstring = orignalstring.replace("original","replaced");
document.getElementById("test").innerHTML = newstring;
Basically, this will identify the entire content of the whole div, then find certain text and replace those terms, like you asked. If you want to replace multiple strings in one command, try this: How to replace multiple strings with the .replace() Method?. This is a question I asked a few weeks back about .replace().
Also, try this JSFiddle: http://jsfiddle.net/tGMaN/
If you want the user to be able to define the text to replace and the replacement text, you can easily do this through text fields or a prompt box, and these values can be stored as variables which are called in the .replace() method.
The String object has lots of useful methods.
var theNewString = theString.replace(findThis, replaceWithThis);
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/replace
// Generates a string of random letters
function generateRandomKey(number) {
var key = String();
var values = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
for(var i = 0; i < number; i++) {
key += values.charAt(Math.floor(Math.random() * values.length));
}
return key;
}
Related
I have a text format like this:
what is your favorite color from these?
Here color can be replaced with anything the user wants. For example food, juice, movie, book, etc.
Now I want to remove the what is your favorite and from these? parts and only want the part that the user has inputted.
I know I can do slice twice to get that. Is there any other elegant solution? like regex?
edit: I am actually making a bot, so I can't use template literals. I need the text as it is and disregard the known portion from it.
Thank you.
You could use a template literal syntax `` to do that.
Example:
var color = document.getElementById('user-input'); // just for the
idea
what is your favorite ${color} from these?
And it will dynamically append the user input inside the string.
Try this :
let defaultVal = 'color';
let str = `what is your favorite ${defaultVal} from these?`;
function getUpdatedVal() {
const val = document.getElementById('val').value;
if (val) {
str = str.replace(defaultVal, val)
}
document.getElementById('result').innerText = str;
defaultVal = val;
}
<input type="text" id="val" onchange="getUpdatedVal()"/>
<p id="result"></p>
Capturing groups is one of the core mechanics in regular expressions. It allow you to get specific part of source text after matching. To solve your problem, you can use this pattern:
what is your favorite (\w+) from these\?
RegEx demo
After matching is success, target word will be in first capturing group.
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.
So I have a java script that finds vowels and capitalizes them. What I want to do is create a id called bigBlue that changes the capitalized values into blue characters with specific css properties.
var strMessage1 = Emphathy;
var startDiv = '<div id="bigBlue">';
var endDiv = '</div>';
var newRoot = strMessage1
.replace(/a/g, startDiv+'A'+endDiv)
.replace(/e/g, startDiv+'E'+endDiv)
.replace(/i/g, startDiv+'I'+endDiv)
.replace(/o/g, startDiv+'O'+endDiv)
.replace(/u/g, startDiv+'U'+endDiv)
$("#test").append(newRoot);
Here is the with the result JsFiddle
My output is pretty much broken gibberish. What im thinking is that the .replace is also replacing the properties of the startDiv and endDiv.
How do I avoid the replacement of the startDiv and endDiv values, while replacing the vowels with the capital vowels, inclosed in the big blue div?
try use function to replace instead direct symbols like that
var newRoot = strMessage1.replace(/[aeiou]/g, function(sym){return startDiv+sym.toUpperCase()+endDiv});
sample on jsfiddle
if you want that chars was on one line - use <span> instead of <div>
Pulling data with AJAX, into an array, everuthing there works fine, then I have this...
$.each(data, function (key, value){
var add = value[5]+value[6];
var sub = add.replace(" ","");
var link = 'http://'+sub+'.mydomain.com';
}
//OUTPUT: http://RR1 Box 22USHIGHWAY 67.NextHomeTown.com
This isn't working. It's not replacing any space characters.
Now, here's where it gets fun. This works on every other DB entry that is returned that has a space. Crazy, right?
Is there some type of character encoding that might be causing it not to recognize the space character that is used in this particular entry? The MySQL table has them entered as varchar, but at this point in the process, they're both just text strings right? So it shouldn't matter.
This will only replace the first spacebar it will match. Use this to replace all spacebars:
var sub = add.replace(/\s/g,"");
Since you report the desired behaviour with other tables, it's perhaps not relevant - but don't forget that in javascript, the string replace function only replaces the first instance of the searchString, unless you use a regular expression.
"red, red, red".replace(/ /g, "");
"red,red,red"
"red, red, red".replace(" ", "");
"red,red, red"
I'm attempting to parse a text string with jQuery and to make a variable out of it. The string is below:
Publications Deadlines: armadllo
I'm trying to just get everything past "Publications Deadlines: ", so it includes whatever the name is, regardless of how long or how many words it is.
I'm getting the text via a the jQuery .text() function like so:
$('.label_im_getting').text()
I feel like this may be a simple solution that I just can't put together. Traditional JS is fine as well if it's more efficient than JQ!
Try this,
Live Demo
First part
str = $.trim($('.label_im_getting').text().split(':')[0]);
Second part
str = $.trim($('.label_im_getting').text().split(':')[1]);
var string = input.split(':') // splits in two halfs based on the position of ':'
string = input[1] // take the second half
string = string.replace(/ /g, ''); // removes all the spaces.