How to copy text between 2 symbols[keywords] in JavaScript? - javascript

How do I replace text between 2 symbols, in my case "." and "/" (without the quotes)
While doing some research at Stack, I found some answers, but they didn't help much.
I think the problem is using common operators as a part of string.
I tried using split
var a = "example.com/something"
var b = a.split(/[./]/);
var c = b[0];
I also tried this:
srctext = "example.com";
var re = /(.*.\s+)(.*)(\s+/.*)/;
var newtext = srctext.replace(re, "$2");
But the above 2 didn't seem to work.
I would be real glad if someone were to solve the question and please explain the use of escape sequences using an example or two. For a side note, I tried Googling it up but the data was not too helpful for me.

Try this code.
var a = "example.com/something";
var textToChange = 'org';
var result = a.replace(/(\.)([\w]+)(\/)/, '$1' + textToChange + '$3');
result will be example.org/something
$1 equals .
$2 is the string you want to change
$3 equals /
Currently I only assumed the text you want to change is mixture of alphabets. You can change [\w]+ to any regular expression to fit the text you want to change.

The example given in your question will work if you make a small change
var a = "example.com/something"
var b = a.split(/[./]/);
var c = b[1];
alert(c);
b[1] will give you string between . and / not b[0]

You can use RegEx \..*?\/ with String#replace to remove anything that is between the . and /.
"example.com/something".match(/\.(.*?)\//)[1] // com
RegEx Explanation:
\.: Match . literal
(.*?): Match anything except newline, non-greedy and add it in first captured group
\/: Match forward slash

something as simple as
var a = "example.com/something"
var c = a.substring( a.indexOf( "." ) + 1, a.indexOf( "/", a.indexOf( "." ) ) );
alert(c);
for replacing,
a = a.replace( c, "NEW" );
alert(a);
to replace it with quotes
a = a.replace( c, "\"\"" );
alert(a);

Related

Regex match cookie value and remove hyphens

I'm trying to extract out a group of words from a larger string/cookie that are separated by hyphens. I would like to replace the hyphens with a space and set to a variable. Javascript or jQuery.
As an example, the larger string has a name and value like this within it:
facility=34222%7CConner-Department-Store;
(notice the leading "C")
So first, I need to match()/find facility=34222%7CConner-Department-Store; with regex. Then break it down to "Conner Department Store"
var cookie = document.cookie;
var facilityValue = cookie.match( REGEX ); ??
var test = "store=874635%7Csomethingelse;facility=34222%7CConner-Department-Store;store=874635%7Csomethingelse;";
var test2 = test.replace(/^(.*)facility=([^;]+)(.*)$/, function(matchedString, match1, match2, match3){
return decodeURIComponent(match2);
});
console.log( test2 );
console.log( test2.split('|')[1].replace(/[-]/g, ' ') );
If I understood it correctly, you want to make a phrase by getting all the words between hyphens and disallowing two successive Uppercase letters in a word, so I'd prefer using Regex in that case.
This is a Regex solution, that works dynamically with any cookies in the same format and extract the wanted sentence from it:
var matches = str.match(/([A-Z][a-z]+)-?/g);
console.log(matches.map(function(m) {
return m.replace('-', '');
}).join(" "));
Demo:
var str = "facility=34222%7CConner-Department-Store;";
var matches = str.match(/([A-Z][a-z]+)-?/g);
console.log(matches.map(function(m) {
return m.replace('-', '');
}).join(" "));
Explanation:
Use this Regex (/([A-Z][a-z]+)-?/g to match the words between -.
Replace any - occurence in the matched words.
Then just join these matches array with white space.
Ok,
first, you should decode this string as follows:
var str = "facility=34222%7CConner-Department-Store;"
var decoded = decodeURIComponent(str);
// decoded = "facility=34222|Conner-Department-Store;"
Then you have multiple possibilities to split up this string.
The easiest way is to use substring()
var solution1 = decoded.substring(decoded.indexOf('|') + 1, decoded.length)
// solution1 = "Conner-Department-Store;"
solution1 = solution1.replace('-', ' ');
// solution1 = "Conner Department Store;"
As you can see, substring(arg1, arg2) returns the string, starting at index arg1 and ending at index arg2. See Full Documentation here
If you want to cut the last ; just set decoded.length - 1 as arg2 in the snippet above.
decoded.substring(decoded.indexOf('|') + 1, decoded.length - 1)
//returns "Conner-Department-Store"
or all above in just one line:
decoded.substring(decoded.indexOf('|') + 1, decoded.length - 1).replace('-', ' ')
If you want still to use a regular Expression to retrieve (perhaps more) data out of the string, you could use something similar to this snippet:
var solution2 = "";
var regEx= /([A-Za-z]*)=([0-9]*)\|(\S[^:\/?#\[\]\#\;\,']*)/;
if (regEx.test(decoded)) {
solution2 = decoded.match(regEx);
/* returns
[0:"facility=34222|Conner-Department-Store",
1:"facility",
2:"34222",
3:"Conner-Department-Store",
index:0,
input:"facility=34222|Conner-Department-Store;"
length:4] */
solution2 = solution2[3].replace('-', ' ');
// "Conner Department Store"
}
I have applied some rules for the regex to work, feel free to modify them according your needs.
facility can be any Word built with alphabetical characters lower and uppercase (no other chars) at any length
= needs to be the char =
34222 can be any number but no other characters
| needs to be the char |
Conner-Department-Store can be any characters except one of the following (reserved delimiters): :/?#[]#;,'
Hope this helps :)
edit: to find only the part
facility=34222%7CConner-Department-Store; just modify the regex to
match facility= instead of ([A-z]*)=:
/(facility)=([0-9]*)\|(\S[^:\/?#\[\]\#\;\,']*)/
You can use cookies.js, a mini framework from MDN (Mozilla Developer Network).
Simply include the cookies.js file in your application, and write:
docCookies.getItem("Connor Department Store");

Remove all content after last '\' is not working

I'm trying to rename a document, I want to remove all the content after the last '\' and then give it another name.
I did it like this but it doesn't seem to be working:
var newDocName = documentPath.replace(/\/$/, '');
var newDocName = newDocName + "\test.pdf";
The '\' doesn't get removed after the first line of code.
Any idea what am I doing wrong?
/\/$/ means you want to match a / if it's the last character in the string meaning this code would replace the very last / if, and only if, it's at the end of the string.
If you want to remove the content after the last \ then you can use a combination of split to split the string on \s then use slice to get everything but the last element. Finally, use join to bring them all back together.
var uri = 'path\\to\\my\\file.ext';
var parts = uri.split('\\');
var withoutFile = parts.slice(0, parts.length - 1);
var putItBackTogether = withoutFile.join('\\');
var voila = putItBackTogether + '\\new-file.name';
console.log(voila);
It is forward slash, use \\ istead.
Try to substitute it for:
var newDocName = documentPath.replace(/\\/$/, '');
Your REGEX has a bad format: you should escape your backquotes (\).
So it may be:
var newDocName = documentPath.replace(/[\\/]$/, '');
var newDocName = newDocName + "\\test.pdf";
This regular expression will search for \ or / at the end ($) of you path. You could use regex101 to test your regular expressions.
You also should consider not using regular expressions when you don’t need them:
var newDocName = documentPath[documentPath.length - 1] == "\\" ? documentPath + "test.pdf" : documentPath + "\\test.pdf";

String : Replace function with expression in Javascript

A string representing a currency is to be converted to a number.
For example:
Input : "125.632.454.454.403,51"
Output expected : 125632454454403.51
Currently I am trying:
Trial 1)
a = "125.632.454.454.403,51";
a.replace(/./, '');
Result = "25.632.454.454.403,51"
Trial 2)
a = "125.632.454.454.403,51";
a.replace(/./g, '');
Result = ""
But I expect the replace function to find all the occurrences of "." and replace by "".
Trial 3)
a = "125.632.454.454.403,51";
a.replace(/,/, '');
Result = "125.632.454.454.40351"
I would be glad if I find a fix for this.
You need to use \. instead of .. The dot (.) matches a single character, without caring what that character is. Also you can do it with single replace() with callback .
var str = "125.632.454.454.403,51";
str = str.replace(/\.|,/g, function(m) {
return m == '.' ? '' : '.'
});
document.write(str);
try:
var str = "125.632.454.454.403,51" ;
var result = str.replace(/\./g,'').replace(/\,/g,'.');
console.log(Number(result))
replace returns the changed string, it does not change it in-place!
You can find this out, by refering to the documentation.
Use
var Result = a.split('.').join("");
console.log(Result);
. has specific meaning in a regex. It matches any character. You need to escape the dot if you are actually looking for the character itself
var a = "125.632.454.454.403,51";
var result = a.replace(/\./g,"");
You can also do (parseFloat(a.replace(/[^0-9]+/g,""))/100)
And if you have to do this for multiple currencies, I would recommend looking into autonumeric.js. It handles all this for you.

Add a string to the thing begin replaced in a case insensitive RegExp.

sorry for the badly formulated question I hope my text and code will make it better understood what I want to accomplish.
I am Writing some java script for an Android app. I have some problems with the JavaScript RegExp for my webview. Could someone please help me?
Basic pseudo code for what I want to do.
/*
* Replace all instances of a letter (case insensitive) with itself + add some string.
* Example, search for all 'a' (case insensitive) and replace it with 'a
* someString' if it was lowercase. If it was a capital than replace it with 'A someString'
*/
This is my code (Sorry its all in a string, has to be for the webview).
"var alpha = 'abcdefghijklmnopqrstuvwxyz'.split('');" +
"for (i = 0; i < 5; i++) " +
"{if(window.HtmlViewer.isActive(i))" +
"{var re = new RegExp( \"(\" + alpha[i] + \"(?![^<>]*>))\", 'gi' );" +
"document.body.innerHTML = document.body.innerHTML.replace(re, " +
"'<font color=\"'+colorsArray[i]+'\">'+alpha[i]+'</font>');}" +
"else{break;}" +
"};" +
In the first loop it replaces all 'a' and 'A' with 'a' and gives a color to it. What I want is to make it replace 'a' with only 'a' and 'A' with only 'A', i.e. the only thing changing is the color "font color="'+colorsArray[i]). Any idea how I would accomplish this? Can I somehow use the var re to get if its a capital or lowercase, and than do something like:
"'<font color=\"'+colorsArray[i]+'\">'+re.getString()+'</font>');}" +
The solution I have now is to make two for loops and remove the 'i' (case insensitive) modifier. In the first loop I handle lowercase and in the second loop I handle uppercase. But this seems like double work since the color for both 'a' and 'A' are the same. There has to be a better way to do this than that?
First off, you don't have to use the loop to match each letter, you can use the regex pattern [a-z] with the 'i' flag to instead of "alpha[i]". I have set up an example that should work for your case here:
http://jsfiddle.net/yy6we65a/3/
var re = /([a-z](?![^<>]*>))/gi;
var colors = ["red","blue","green","yellow","orange"];
var i =0;
function encapsulate(src){
var ret = '<font color="'+colors[i]+'">'+src+'</font>';
i++;
if( i == 5) i = 0;
return ret;
}
var orig = document.getElementById("container").innerHTML;
var target = document.getElementById("target");
target.innerHTML = orig.replace(re,encapsulate);
I didn't have your color array, so I used one of my own but of course you can just use yours. There are comments in the code to explain each section.

JavaScript manipulate string problem

var a
var a = "ACdA(a = %b, ccc= 2r2)";
var b
var b = "\ewfsd\ss.jpg"
Expected outputs:
var c = "ACdA(a = %b, ccc= 2r2, b_holder = \ewfsd\ss.jpg)"
It adds the string b to the end of string a, that's it! But be careful of the ")"
"b_holder " is hard coded string, it's absolutly same in all cases, won't be changed.
Thanks everyone!
You need to do two things:
Concatenate ", b_holder = " to var b, and
Replace ")" in var a with the result of the concatenation.
Since this is homework, I'll leave it to you to figure out which methods to use. Good luck!
Hint: you can either store the result of the concatenation in step (1) in another variable, or you can do it all in one line.
Edit: You also need to concatenate the ")" back onto the end. So maybe three things. :-)
You still don't show any code for what you're doing with a and b to produce c; you are just showing a simple assignment of the expected (desired) value.
You have a problem, however with the value you're assigning to var b -- because the backslash \ is an escape. If you want a backslash in the actual string you need to double it, so your assignment would be
var b = "\\ewfsd\\ss.jpg";
var a = "ACdA(a = %b, ccc= 2r2)";
var b = "\\ewfsd\\ss.jpg"; // need to escape the backslash for RegExp replace
var re = /\)$/;
var c = a.replace(re, ", b_holder = "+b+"\)");

Categories

Resources