Detect presence of a specific pattern in Javascript String - javascript

How can i do to search if a Javascript String contains the following pattern :
"#aRandomString.temp"
I would like to know if the String contains # character and then any String and then ".temp" string.
Thanks

This one liner should do the job using regex#test(Strng):
var s = 'foo bar #aRandomString.temp baz';
found = /#.*?\.temp/i.test(s); // true

Use indexOf to find a string within a string.
var string = "#aRandomString.temp";
var apos = string.indexOf("#");
var dtemp = string.indexOf(".temp", apos); // apos as offset, invalid: ".temp #"
if (apos !== -1 && dtemp !== -1) {
var aRandomString = string.substr(apos + 1, dtemp - apos);
console.log(aRandomString); // "aRandomString"
}

You can try this
var str = "#something.temp";
if (str.match("^#") && str.match(".temp$")) {
}
demo

You can use the match function.
match expects the regular expression.
function myFunction()
{
var str="#someting.temp";
var n=str.test(/#[a-zA-Z]+\.temp/g);
}
Here is a demo: http://jsbin.com/IBACAB/1

Related

How to replace/remove some part of a string

I have a string in which i want to remove some part.
1) below is the string( Encrypted message)
##_/profiles/c3ed4acd-b3be-487e-81b4-a27643745d^^____User1__###^^^ says hello to ##_/profiles/d3ac3c5a-8a9f-4640-8563-127674d93e^^____User2__###^^^
I want to get below 2 things from this
a) A string
#User1 says to #User2
2) A json object like
{
"c3ed4acd-b3be-487e-81b4-a27643745d":"User1",
"d3ac3c5a-8a9f-4640-8563-127674d93e":"User2"
}
First I tried to get string and used below approach using regex
I have tried it by doing like this
var str = "##___/profiles/c3ed4acd-b3be-487e-81b4-a27643745d__^^____User1__###^^^ says to ##___/profiles/d3ac3c5a-8a9f-4640-8563-127674d93e__^^____User2__###^^^"
var rx = /(^##___|,###^^^)/; // start with ##___ and end with ###^^^
var expectedString = str.replace(/(^##___|,###^^^)/g, "");
console.log(expectedString);
But this is just replace first occurance of
There are some fundamental problems in your code
you have to escape the ^ character as \^
you don't even use your rx variable
pipe character | means or, not start with and end with
try this:
// a)
var str = "##___/profiles/c3ed4acd-b3be-487e-81b4-a27643745d__^^____User1__###^^^ says to ##___/profiles/d3ac3c5a-8a9f-4640-8563-127674d93e__^^____User2__###^^^"
var rx = /##___([^_]+)__\^\^____([^_]+)__###\^\^\^/g;
var expectedString = str.replace(rx, "#$2");
console.log(expectedString);
// b)
var list = {};
while ((m = rx.exec(str)) !== null) {
if (m.index === rx.lastIndex) {
rx.lastIndex++;
}
list[m[1]] = m[2];
}
console.log(list);

jQuery replace match word with each method

How do i replace the text with each method?
Is it right? it doesnt replace / find the text correctly
$(function(){
var style_find = ['tab-1','tab-2','rounded-1','rounded-2','tabs-1','tabs-2','tabs-alt-1','tabs-alt-2','tab-alt-1','tab-alt-2'];
var cur_style = $('#obj').attr('class');
var new_style;
$(style_find).each(function(i,cl){
new_style = cur_style.replace(cl,'new-class');
// it doesnt replace the whole word
});
})
String.prototype.replace() behaves differently depending upon the type of it's first parameter. Consider this code:
var example = "str str str str";
example = example.replace("str", "bob");
console.log(example === "bob str str str"); // === true?
I gave replace() a string for it's first parameter. When you do so, it only replaces the first occurrence of the substring.
When you call replace() with a RegExp you get something that returns all matches replaced
var example = "str str str str";
example = example.replace(/str/g, "bob");
console.log(example === "bob bob bob bob"); // === true
What we need is a regexp that matches everything you want to replace.
var style_find = ['tab-1','tab-2','rounded-1','rounded-2','tabs-1','tabs-2','tabs-alt-1','tabs-alt-2','tab-alt-1','tab-alt-2'];
var regexp = (function() {
var inner = "";
style_find.forEach(function(el) {
inner = inner + el + "|";
});
return new RegExp(inner, "g");
}());
With regexp I can modify your code to:
$(function(){
var style_find = ['tab-1','tab-2','rounded-1','rounded-2','tabs-1','tabs-2','tabs-alt-1','tabs-alt-2','tab-alt-1','tab-alt-2'];
var cur_style = $('#obj').attr('class');
var new_style = cur_style.replace(regexp, 'new-class');
});

convert regex string to regex object in javascript

I am getting regex string from json object (yes its dynamic and will be always be string) i want to test this with textbox value.
But even if i pass valid input text it does not pass regex condition
code :
var pattern = "/^[A-Za-z\s]+$/";
var str = "Some Name";
pattern = new RegExp(pattern);
if(pattern.test(str))
{
alert('valid');
}
else
{
alert('invalid');
}
Fiddle :- http://jsfiddle.net/wn9scv3m/
Two problems:
You need to escape the backslash.
You need to remove the forward slashes on the beginning and end of string.
Corrected code:
var pattern = "^[A-Za-z\\s]+$";
var str = "Some Name";
pattern = new RegExp(pattern);
if(pattern.test(str))
{
alert('valid');
}
else
{
alert('invalid');
}
http://jsfiddle.net/wn9scv3m/3/
Use regex-parser:
const parseRegex = require("regex-parser")
parseRegex("/^hi$/g")
// => /^hi$/g
This should work for you (jsfiddle: http://jsfiddle.net/wn9scv3m/9/):
var pattern = /^[(\w)|(\s)]+$/; // using / regex constructor...
var altPattern = "^[(\w)|(\s)]+$"; // using quotes and new RegEx() syntax...
var regex = new RegExp(altPattern);
var str = "Some Name";
if (str.match(pattern) != null && regex.test(str) != null) { // check using both methods
alert('valid');
}
else {
alert('invalid');
}
As far as I can see in https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions you are combining two methods to declare RegExp. If you are using the string variant, then don't include the "/" character before and after the expression, example:
var pattern = "^[A-Za-z\s]+$";
pattern = new RegExp(pattern);
If you like the /regexp/ form better, then use it without quotes:
pattern = /^[A-Za-z\s]+$/;
this should work
var str1 = "SomeName"; //true
var str2 = "SomeName123"; //false
function MyRegex(val) {
var pattern = /^[A-Za-z\s]+$/;
var match = pattern.exec(val);
return match !== null && match[0] === val;
}
alert(MyRegex(str1));
alert(MyRegex(str2));

Regular Expression in JS

How do you trim all of the text after a comma using JS?
I have: string = Doyletown, PA
I want: string = Doyletown
var str = 'Doyletown, PA';
var newstr=str.substring(0,str.indexOf(',')) || str;
I added the || str to handle a scenario where the string has no comma
How about a split:
var string = 'Doyletown, PA';
var parts = string.split(',');
if (parts.length > 0) {
var result = parts[0];
alert(result); // alerts Doyletown
}
using regular expression it will be like:
var str = "Doyletown, PA"
var matches = str.match(/^([^,]+)/);
alert(matches[1]);
jsFiddle
btw: I would also prefer .split() method
Or more generally (getting all the words in a comma separated list):
//Gets all the words/sentences in a comma separated list and trims these words/sentences to get rid of outer spaces and other whitespace.
var matches = str.match(/[^,\s]+[^,]*[^,\s]+/g);
Try this:
str = str.replace(/,.*/, '');
Or play with this jsfiddle

Delete first character of string if it is 0

I want to delete the first character of a string, if the first character is a 0. The 0 can be there more than once.
Is there a simple function that checks the first character and deletes it if it is 0?
Right now, I'm trying it with the JS slice() function but it is very awkward.
You can remove the first character of a string using substring:
var s1 = "foobar";
var s2 = s1.substring(1);
alert(s2); // shows "oobar"
To remove all 0's at the start of the string:
var s = "0000test";
while(s.charAt(0) === '0')
{
s = s.substring(1);
}
Very readable code is to use .substring() with a start set to index of the second character (1) (first character has index 0). Second parameter of the .substring() method is actually optional, so you don't even need to call .length()...
TL;DR : Remove first character from the string:
str = str.substring(1);
...yes it is that simple...
Removing some particular character(s):
As #Shaded suggested, just loop this while first character of your string is the "unwanted" character...
var yourString = "0000test";
var unwantedCharacter = "0";
//there is really no need for === check, since we use String's charAt()
while( yourString.charAt(0) == unwantedCharacter ) yourString = yourString.substring(1);
//yourString now contains "test"
.slice() vs .substring() vs .substr()
EDIT: substr() is not standardized and should not be used for new JS codes, you may be inclined to use it because of the naming similarity with other languages, e.g. PHP, but even in PHP you should probably use mb_substr() to be safe in modern world :)
Quote from (and more on that in) What is the difference between String.slice and String.substring?
He also points out that if the parameters to slice are negative, they
reference the string from the end. Substring and substr doesn´t.
Use .charAt() and .slice().
Example: http://jsfiddle.net/kCpNQ/
var myString = "0String";
if( myString.charAt( 0 ) === '0' )
myString = myString.slice( 1 );
If there could be several 0 characters at the beginning, you can change the if() to a while().
Example: http://jsfiddle.net/kCpNQ/1/
var myString = "0000String";
while( myString.charAt( 0 ) === '0' )
myString = myString.slice( 1 );
The easiest way to strip all leading 0s is:
var s = "00test";
s = s.replace(/^0+/, "");
If just stripping a single leading 0 character, as the question implies, you could use
s = s.replace(/^0/, "");
You can do it with substring method:
let a = "My test string";
a = a.substring(1);
console.log(a); // y test string
Did you try the substring function?
string = string.indexOf(0) == '0' ? string.substring(1) : string;
Here's a reference - https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/substring
And you can always do this for multiple 0s:
while(string.indexOf(0) == '0')
{
string = string.substring(1);
}
One simple solution is to use the Javascript slice() method, and pass 1 as a parameter
let str = "khattak01"
let resStr = str.slice(1)
console.log(resStr)
Result : hattak01
var s = "0test";
if(s.substr(0,1) == "0") {
s = s.substr(1);
}
For all 0s: http://jsfiddle.net/An4MY/
String.prototype.ltrim0 = function() {
return this.replace(/^[0]+/,"");
}
var s = "0000test".ltrim0();
const string = '0My string';
const result = string.substring(1);
console.log(result);
You can use the substring() javascript function.
//---- remove first and last char of str
str = str.substring(1,((keyw.length)-1));
//---- remove only first char
str = str.substring(1,(keyw.length));
//---- remove only last char
str = str.substring(0,(keyw.length));
try
s.replace(/^0/,'')
console.log("0string =>", "0string".replace(/^0/,'') );
console.log("00string =>", "00string".replace(/^0/,'') );
console.log("string00 =>", "string00".replace(/^0/,'') );
Here's one that doesn't assume the input is a string, uses substring, and comes with a couple of unit tests:
var cutOutZero = function(value) {
if (value.length && value.length > 0 && value[0] === '0') {
return value.substring(1);
}
return value;
};
http://jsfiddle.net/TRU66/1/
String.prototype.trimStartWhile = function(predicate) {
if (typeof predicate !== "function") {
return this;
}
let len = this.length;
if (len === 0) {
return this;
}
let s = this, i = 0;
while (i < len && predicate(s[i])) {
i++;
}
return s.substr(i)
}
let str = "0000000000ABC",
r = str.trimStartWhile(c => c === '0');
console.log(r);
Another alternative to get the first character after deleting it:
// Example string
let string = 'Example';
// Getting the first character and updtated string
[character, string] = [string[0], string.substr(1)];
console.log(character);
// 'E'
console.log(string);
// 'xample'
From the Javascript implementation of trim() > that removes and leading or ending spaces from strings. Here is an altered implementation of the answer for this question.
var str = "0000one two three0000"; //TEST
str = str.replace(/^\s+|\s+$/g,'0'); //ANSWER
Original implementation for this on JS
string.trim():
if (!String.prototype.trim) {
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g,'');
}
}
Another alternative answer
str.replace(/^0+/, '')
var test = '0test';
test = test.replace(/0(.*)/, '$1');

Categories