Replace any words with modified version of themselves - javascript

I'm looking for an easy way to turn this string:
(java || javascript) && vbscript
Into this string:
(str.search('java') || str.search('javascript')) && str.search('vbscript')
ie replace each word in the string with str.search('" + word + "')
I've looked at mystring.match(/[-\w]+/g); which will pull any words out into an array (but not their position)

You can call replace:
mystring.replace(/[-\w]+/g, "str.search('$&')");
Note that this is an XSS hole, since the user input can contain 's.

Just a fixed version with correct capture and using 1 as backtrack index. See details in "Specifying a string as a parameter" section of String.replace.
mystring.replace(/([-\w]+)/g, "str.search('$1')");

Related

Cant Find the position of a letter in the string

I got a string Like this
var test = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
Actually I can't find the position of "t" in this string. don't know why,
I used indexOf, tried to convert this into string object, but all got in vain
note : Please use the exact string given in the question,
Thanks,
These are non-standard characters, so to search for the "t" in in, you have to actually copy and paste the t from your string.
>> test.indexOf("t")
>> 29
For demonstration:
"t".charCodeAt()
116 // ASCII code for lowercase t
"t".charCodeAt()
65364 // Something non-standard
You can't find because it's not 't' you are trying to find. Take a look at "t".charCodeAt(0) which returns 65364 and "t".charCodeAt(0) which yields 116. Those are different characters.
Use String.prototype.indexOf() which will return the index within the calling String object of the first occurrence of the specified value.
Please note that t in your string is a "non-standard character" and won't be found by indexOf() if you use a "standard character ".
More information here: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf
var test = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
console.log(test.indexOf("t"));

Regex to extract two digits from phone number

I am trying to take only 2 characters from my phone no.
I have used regex match ^\+55 and this will return the following example.
Phone No : +5546342543
Result : 46342543
Expected Result was only 46.
I don't want to use substring for the answer instead I want to extract that from the phone no with regex.
Can anybody help me on this.
Thank you.
The pattern you used - ^\+55 - matches a literal + in the beginning of the string and two 5s right after.
46 is the substring that appears right after the initial +55. In some languages, you can use a look-behind (see example) to match some text preceded with another.
JavaScript has no look-behind support, so, you need to resort to capturing groups.
You can use string#match or RegExp#exec to obtain that captured text marked with round brackets:
var s = '+5546342543';
if ((m=/^\+55(\d{2})/.exec(s)) !== null) {
document.write(m[1]);
}
This example handles the case when you get no match.
Just try with:
'+5546342543'.match(/^\+55(\d{2})/)[1];
This will get what you want
"+5546342543".match(/^\+55(.*)/)[1]
This solves your problem ?
phoneNumber = "+5546342543"
phone = phoneNumber.substr(3) // returns "46342543"
twoDigits = phoneNumber.substr(3,2) // returns "46"
Using the substr() method as quoted :
The substr() method returns the characters in a string beginning at the specified location through the specified number of characters.
Syntax: str.substr(start[, length])
Source : Mozilla MDN

Returning a String with whitespaces

I am using the below string and I want to return the substring with the blankspaces in javascript.
How can I do this?
As of now I used the normal substring function but its giving me the result after removing the blankspaces.
var Sting="CREC 20140615001CREC_GLOSS 18_0000033122 GLO4265 SGLB201406152014090120140531 TESTFOREF 0000000000033122 8-1 EQTY GB 21419 ACTUALS EUR000000000462098830 8738 N C70390000501F SQTY BUY 212102 49500.00# 9.34 8738 8738 "
var x= Sting.substring(1,27)
Result x= CREC 20
I don't want it like this, rather, I want my result to be
x= CREC 20
This is a browser thing - consecutive spaces are displayed as one. You might want to replace ' ' with and then it will display all spaces indiviudaly
x.replace(" ", " ");
Another way is to avoid displaying the string as HTML. For example the alert() function will show the correct number of spaces without the need to replace. Also displaying the string within a <pre> tag should work fine too.
I think Dobromir's interpretation of the OP is probably correct, and therefore a good answer.
If it is indeed a browser thing, then perhaps a better way to get it to display properly without changing the string itself is to style the HTML element with
white-space: pre
This will preserve the spaces like it does in a <pre> block.
See http://www.w3schools.com/cssref/pr_text_white-space.asp
If your spaces are always the same length you could do:
x.replace(" ", " ");
otherwise you can use a regular expression to replace multiple spaces with one:
x.replace(/\s+/g, ' ');
as seen Here

Regex - Delete up to second whitespace

I think what i'm trying to do is possible... but I haven't found an answer that achieves that yet.
I would like to format a string which will be similar to this in javascript:
+44 (0) 234-567-8901
The proceeding international ( +44 ) and local ( (0) ) calling code are subject to change, so the string could be longer or shorter. However the format is always the same.
I would like to take this string and remove all characters including whitespaces up to the second whitespace and remove dashes.
e.g:
+44 (0) 234-567-8901 becomes 2345678901
Can anyone help?
Thanks
Going by your own requirements (remove everything up to and including the second whitespace, and remove dashes from the remaining);
Use this pattern ^([\S]+\s){2}|- and replace with nothing. You should be left with a number similar to what you asked for (+44 (0) 234-567-8901 becomes 2345678901).
If you can rely on the ending format of the string to be a consistent number of characters, you can grab the last 12 characters, and remove the dashes.
var result = str.slice(-12).replace(/-/g, "");
If you really just want a regex, you can do this...
var result = str.match(/(\d{3})-(\d{3})-(\d{4})$/).slice(1).join("");
Again, this relies on consistency of the end of the string. If there may be variation, you'll need to adjust to compensate.
To get everything after the last whitespace, change the slice() in the first example to this...
.slice(str.lastIndexOf(' ') + 1)
To get everything after the second whitespace, change the slice() to this...
.slice(str.indexOf(' ', str.indexOf(' ') + 1) + 1)

Selenium adding weird characters to the end of javascript in a form field

I'm trying to set up a field to prepopulate with a unique set of characters, so that i can automatically generate test accounts. Because of the way the system is set up, the name field must be unique, and must not include numerical characters.
I put together this selenium code, and it works 99% of the way, but leaves extra garbage characters at the end of the good code.
javascript{stringtime='';
nowtime=new Date().getTime().toString();
for ( var i in nowtime )
{ stringtime+=String.fromCharCode(parseInt(nowtime[i])+65 ); };
'test' + stringtime + '\0'}
Result:
testBCEBBJCBFBBAI + a bunch of characters that won't copy into here. They look like 4 zeros in a box.
Thanks in advance for the help.
Excluding the '\0' character at the end, which shows up at a ?, and within Selenium, I think it's javascript engine is having trouble processing the for(var i in nowtime).
Try it like this:
javascript{
stringtime= '';
nowtime=new Date().getTime().toString();
for(var i = 0; i < nowtime.length; i++){
stringtime += String.fromCharCode(parseInt(nowtime[i])+65);
}
stringtime;
}
Those characters are ones that are outside the standard ASCII that your font can't reproduce. Those numbers signify which character it is. If its 4 zeros, its that \0 char you are putting on at the end. I don't know the language, but it doesn't look like you need that.
Also your random number generator is a bit flawed. Have a look here:
http://www.mediacollege.com/internet/javascript/number/random.html

Categories