Javascript Value Replace for Multiple Values - javascript

I am trying to replace multiple values in a string with JS replace(). The values that I want to replace include line breaks, &, #, etc... I know how to replace one value:
var string = document.getElementById('string').value.replace(\/n/g, '<br>');
However, what is the syntax to include other values. For example, how can I make the below replace functions one function?
var string = document.getElementById('string').value.replace(\/n/g, '<br>')
var string = document.getElementById('string').value.replace('&', '%26');

You could chain it simply.
var string = document.getElementById('string').value.replace(/\n/g, '<br>').replace('&', '%26');

Related

How to get a specific part of a string in Javascript?

I have a string:
string = 'XXXXXXXXXXXXtext:hello,XXXXXXX'
I want to retrieve hello. XXXXXXXX is some random text. The only thing I know is that hello is between text: and ,.
You can use a regular expression to retrieve the text you need. Try this:
var str = 'XXXXXXXXXXXXtext:hello,XXXXXXX';
var matches = /text\:(.+),/gi.exec(str);
console.log(matches[1]);
If there are multiple instances of text: within your string then you can use a loop to iterate through the result of exec() and retrieve them all.

Extract Twitter handlers from string using regex in JavaScript

I Would like to extract the Twitter handler names from a text string, using a regex. I believe I am almost there, except for the ">" that I am including in my output. How can I change my regex to be better, and drop the ">" from my output?
Here is an example of a text string value:
"PlaymakersZA, Absa, DiepslootMTB"
The desired output would be an array consisting of the following:
PlaymakersZA, Absa, DiepslootMTB
Here is an example of my regex:
var array = str.match(/>[a-z-_]+/ig)
Thank you!
You can use match groups in your regex to indicate the part you wish to extract.
I set up this JSFiddle to demonstrate.
Basically, you surround the part of the regex that you want to extract in parenthesis: />([a-z-_]+)/ig, save it as an object, and execute .exec() as long as there are still values. Using index 1 from the resulting array, you can find the first match group's result. Index 0 is the whole regex, and next indices would be subsequent match groups, if available.
var str = "PlaymakersZA, Absa, DiepslootMTB";
var regex = />([a-z-_]+)/ig
var array = regex.exec(str);
while (array != null) {
alert(array[1]);
array = regex.exec(str);
}
You could just strip all the HTML
var str = "PlaymakersZA, Absa, DiepslootMTB";
$handlers = str.replace(/<[^>]*>|\s/g,'').split(",");

RegExp match a single quoted text without quotes - JavaScript

I'm sorry if it is a confusing question. I was trying to find a way to do this but couldn't find it so, if it is a repeated question, my apologies!
I have a text something like this: something:"askjnqwe234"
I want to be able to get askjnqwe234 using a RegExp. You can notice I want to omit the quotes. I was trying this using /[^"]+(?=(" ")|"$)/g but it returns an array. I want a RegExt to return a single string, not an array.
I don't know if it's possible but I do not want to specify the position of the array; something like this:
var x = string.match(/[^"]+(?=(" ")|"$)/g)[0];
Thanks!
Try:
/"([^"]*)"/g
in English: look for " the match and record anything that isn't " till you see another "".
match and exec always return an array or null, so, assuming you have a single double-quoted value and no newlines in the string, you could use
var x;
var str = 'something:"askjnqwe234"';
x = str.replace( /^[^"]*"|".*/g, '' );
// "askjnqwe234"
Or, if you may have other quoted values in the string
x = str.replace( /.*?something:"([^"]*)".*/, '$1' );
where $1 refers to the substring captured by the sub-pattern [^"]* between the ().
Further explanation on request.
Notwithstanding the above, I recommend that you tolerate the array indexing and just use match.
You can capture the information inside quotes like this, assuming it matches:
var x = string.match(/something:"([^"]*)"/)[1];
The memory capture at index 1 is the part inside the double quotes.
If you're not sure it will match:
var match = string.match(/something:"([^"]*)"/);
if (match) {
// use match[1] here
}

string replace with jquery assitance

I have a string like this
"/folder1/folder2/folder3/IMG_123456_PP.jpg"
I want to use JavaScript / jQuery to replace the 123456 in the above string with 987654. The entire string is dynamic so cant do a simple string replace. For example, the string could also be
"/folder1/folder2/folder3/IMG_143556_TT.jpg"
"/folder1/folder2/folder3/IMG_1232346_RR.jpg"
Any tips on this?
"/folder1/folder2/folder3/IMG_123456_PP.jpg".replace(/\_\d{2,}/,'_987654');
Edit :
"/fo1/fo2/fol3/IMG_123456fgf_PP.jpg".replace(/\_\d{2,}[A-Za-z]*/,'_987654');
I am sure there is a better way to do this, but if you are trying to always replace the numbers of that file regardless of what they may be you could use a combination of splits/joins like this:
str = "/folder1/folder2/folder3/IMG_143556_TT.jpg" //store image src in string
strAry = str.split('/') //split up the string by folders and file (as last array position) into array.
lastPos = strAry.length-1; //find the index of the last array position (the file name)
fileNameAry = strAry[lastPos].split('_'); //take the file name and split it into an array based on the underscores.
fileNameAry[1] = '987654'; //rename the part of the file name you want to rename.
strAry[lastPos] = fileNameAry.join('_'); //rejoin the file name array back into a string and over write the old file name in the original string array.
newStr = strAry.join('/'); //rejoin the original string array back into a string.
What this will do is make it so that regardless of what directory or original name of the file name is, you can change it based on the string's structure. so as long as the file naming convention stays the same (with underscores) this script will work.
please excuse my vocab, I know it's not very good heh.
Use a regular expression
var str = '/folder1/folder2/folder3/IMG_123456_PP.jpg';
var newstr = str.replace(/(img_)(\d+)(?=_)/gi,function($0, $1){
return $1 ? $1 + '987654' : $0;
});
example at http://www.jsfiddle.net/MZXhd/
Perhaps more comprehensible is
var str = '/folder1/folder2/folder3/IMG_123456_PP.jpg';
var replacewith = '987654';
var newstr = str.replace(/(img_)(\d+)(?=_)/gi,'$1'+replacewith);
example at http://www.jsfiddle.net/CXAq6/

assign matched values from jquery regex match to string variable

I am doing it wrong. I know.
I want to assign the matched text that is the result of a regex to a string var.
basically the regex is supposed to pull out anything in between two colons
so blah:xx:blahdeeblah
would result in xx
var matchedString= $(current).match('[^.:]+):(.*?):([^.:]+');
alert(matchedString);
I am looking to get this to put the xx in my matchedString variable.
I checked the jquery docs and they say that match should return an array. (string char array?)
When I run this nothing happens, No errors in the console but I tested the regex and it works outside of js. I am starting to think I am just doing the regex wrong or I am completely not getting how the match function works altogether
I checked the jquery docs and they say that match should return an array.
No such method exists for jQuery. match is a standard javascript method of a string. So using your example, this might be
var str = "blah:xx:blahdeeblah";
var matchedString = str.match(/([^.:]+):(.*?):([^.:]+)/);
alert(matchedString[2]);
// -> "xx"
However, you really don't need a regular expression for this. You can use another string method, split() to divide the string into an array of strings using a separator:
var str = "blah:xx:blahdeeblah";
var matchedString = str.split(":"); // split on the : character
alert(matchedString[1]);
// -> "xx"
String.match
String.split

Categories

Resources