Cant Find the position of a letter in the string - javascript

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"));

Related

Remove all numbers including floats from string with Javascript

I have these strings with numbers
"$12.3"
"12,3 SEK"
"12 pounds"
In all the occurrences i need to remove the number, float or not, and just keep the rest of the string.
"$"
"SEK"
"pounds"
I found several posts that are similar to my question, like this one:
Removing Numbers from a String using Javascript
Where something like this is suggested in a comment:
"12.3 USD".replace(/\d+([,.]\d+)?/g)
But that only returns (with the Chrome dev console):
"undefined USD"
That's because you aren't telling it what to replace those values with. Try
"12.3 USD".replace(/\d+([,.]\d+)?/g, '')
// replace with an empty string ---^
It looks like you also want to remove any whitespace coming after the numbers so you could modify your regex a bit to do that.
let result = "12.3 USD".replace(/\d+([,.]\d+)?\s*/g, '');
// remove whitespace ---^
console.log(result);

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

replace first occurrence of string after another string

Tried to find it in the network without any success..
Let's say I have the following string:
this is a string test with a lot of string words here another string string there string here string.
I need to replace the first 'string' to 'anotherString' after the first 'here', so the output will be:
this is a string test with a lot of string words here another anotherString string there string here string.
Thank you all for the help!
You don't need to add g modifier while replacing only the first occurance.
str.replace(/\b(here\b.*?)\bstring\b/, "$1anotherString");
DEMO
If you are looking for something which takes in a sentence and replaces the first occurrence of "string" after "here" (using the example in your case),
You should probably look at split() and see how to use it in a greedy way referring to something like this question. Now, use the second half of the split string
Then use replace() to find "string" and change it to "anotherString". By default this function is greedy so only your first occurrence will be replaced.
Concatenate the part before "here" in the original string, "here" and the new string for the second half of the original string and that will give you what you are looking for.
Working fiddle here.
inpStr = "this is a string test with a lot of string words here another string string there string here string."
firstHalf = inpStr.split(/here(.+)?/)[0]
secondHalf = inpStr.split(/here(.+)?/)[1]
secondHalf = secondHalf.replace("string","anotherString")
resStr = firstHalf+"here"+secondHalf
console.log(resStr)
Hope this helps.

How to regex test a string for a pattern while excluding certain characters?

I'm getting nowhere with this...
I need to test a string if it contains %2 and at the same time does not contain /. I can't get it to work using regex. Here is what I have:
var re = new RegExp(/.([^\/]|(%2))*/g);
var s = "somePotentially%2encodedStringwhichMayContain/slashes";
console.log(re.test(s)) // true
Question:
How can I write a regex that checks a string if it contains %2 while not containing any / slashes?
While the link referred to by Sebastian S. is correct, there's an easier way to do this as you only need to check if a single character is not in the string.
/^[^\/]*%2[^\/]*$/
EDIT: Too late... Oh well :P
Try the following:
^(?!.*/).*%2
either use inverse matching as shown here: Regular expression to match a line that doesn't contain a word?
or use indexOf(char) in an if statement. indexOf returns the position of a string or char in a string. If not found, it will return -1:
var s = "test/";
if(s.indexOf("/")!=-1){
//contains "/"
}else {
//doesn't contain "/"
}

Split by regex yield "undefined"

I have a code which extract query string parameters :
So ( for example) if the window url is :
....&a=1&.....
--The code first using split on & and then do split on the =
however , sometimes we use base64 values , which can have extra finals ='s (padding).
And here is where my code is messed up.
the result is N4JOJ7yZTi5urACYrKW5QQ and it should be N4JOJ7yZTi5urACYrKW5QQ==
So I enhance my regex to :
search = such that after it -> ( there is no end OR there is no [=])
'a=N4JOJ7yZTi5urACYrKW5QQ=='.split(/\=(?!($|=))/)
it does work. ( you can run it on console)
but the result is ["a", undefined, "N4JOJ7yZTi5urACYrKW5QQ=="]
Why am I getting undefined
How can i cure my regex for yielding only ["a", "N4JOJ7yZTi5urACYrKW5QQ=="]
p.s.
I know i can replace all the finals ='s to something temporary and then replace it back
but this tag is tagged as regex. So im looking a way to fix my regex.
This happens because you have additional match ($|=). You can exclude it from matching with ?::
"a=N4JOJ7yZTi5urACYrKW5QQ==".split(/=(?!(?:$|=))/);
However, you can always flatten that match and remove extra block:
"a=N4JOJ7yZTi5urACYrKW5QQ==".split(/=(?!$|=)/);
The url needs to be encoded
'a=N4JOJ7yZTi5urACYrKW5QQ=='
should be
'a=N4JOJ7yZTi5urACYrKW5QQ%3D%3D'
Look into encodeURIComponent()
And if you want to use a reg expression to get the key from the value
> "abc=fooo".match(/([^=]+)=?(.*)?/);
["abc=fooo", "abc", "fooo"]
why must you use split? a regex match with two captures, like /^(.+)=(.+)$/ would seem more obvious.

Categories