javascript search string contains ' + ' - javascript

i would to search a string into another string but i'm facing an issue.
There is my code :
reference = "project/+bug/1234";
str = "+bug/1234";
alert(reference.search(str));
//it should alert 8 (index of matched strings)
but it alert -1 : so, str wasn't found into reference.
I've found what's the problem is, and it seems to be the " + " character into str, because .search("string+str") seems to evaluate searched string with the regex " + "

Just use string.indexOf(). It takes a literal string instead of converting the string to a RegExp object (like string.search() does):
> reference = "project/+bug/1234";
> str = "+bug/1234";
> console.log(reference.indexOf(str));
8

Try this:
reference = "project/+bug/1234";
str = "+bug/1234";
alert(reference.indexOf("+bug/1234"));

Related

Reading values with different datatypes inside a string in javascript

Assume i have a string
var str = " 1, 'hello' "
I'm trying to give a function the above values found in str but as integer and string- not as one string-
for example myFunc(1,'hello')
how can i achieve that
i tried using eval(str),
but I'm getting invalid token ,
How can i solve this?
The following should work with any number of arguments.
function foo(num, str) {
console.log(num, str);
}
const input = "1, 'hel,lo'";
const args = JSON.parse('[' + input.replace(/'/g, '"') + ']');
foo(...args);
You've almost got the right idea with eval(str) however, that isn't the thing you actually want to evaluate. If you do use eval(str), it is the same as saying eval(" 1, 'hello' ")
However, what you really want to do is:
eval("func(1, 'hello world')).
To do this you can do:
eval(func.name + '(' + str.trim() + ')');
Here we have:
func.name: The name of the function to call. You can of course hard code this. (ie just write "func(" + ...)
str.trim(): The arguments you want to pass into the given function. Here I also used .trim() to remove any additional whitespace around the string.
Take a look at the snippet below. Here I have basically written out the above line of code, however, I have used some intermediate variables to help spell out how exactly this works:
function func(myNum, myStr) {
console.log(myNum*2, myStr);
}
let str = " 1, 'hello, world'";
// Build the components for the eval:
let fncName = func.name;
let args = str.trim();
let fncStr = fncName + '(' + args + ')';
eval(fncStr);
Alternatively, if you only wish to pass in two arguments you can use .split(',') on your string to split the string based on the comma character ,.
Using split on " 1, 'hello' " will give you an array such as this one a:
let a = [" 1", "'hello'"];
Then cast your string to an integer and remove the additional quotes around your string by using .replace(/'/g, ''); (replace all ' quotes with nothing ''):
let numb = +a[0].trim(); // Get the number (convert it to integer using +)
let str = a[1].trim().replace(/'/g, ''); // get the string remove whitespace and ' around it using trim() and replace()
Now you can call your function using these two variables:
func(numb, str);
function func(myNum, myStr) {
console.log('The number times 2 is:', myNum*2, "My string is:", myStr);
}
let arguments = " 1, 'hello' ";
let arr = arguments.split(',');
let numb = +arr[0].trim(); // Argument 1
let str = arr[1].trim().replace(/'/g, ''); // Argument 2
func(numb, str);

How to grab string(s) before the second " - "?

var string = "bs-00-xyz";
As soon as the second dash has detected, I want to grab whatever before that second dash, which is bs-00 in this case.
I am not sure what is the most efficient way to do that, and here is what I come up with.
JSFiddle = http://jsfiddle.net/bheng/tm3pr1h9/
HTML
<input id="searchbox" placeholder="Enter SKU or name to check availability " type="text" />
JS
$("#searchbox").keyup(function() {
var query = this.value;
var count = (query.match(/-/g) || []).length;
if( count == 2 ){
var results = query.split('-');
var new_results = results.join('-')
alert( "Value before the seond - is : " + new_results );
}
});
You could do it without regex with this
myString.split('-').splice(0, 2).join('-');
In case there are more than two dashes in your string...
var myString = string.substr(0, string.indexOf('-', string.indexOf('-') + 1));
Using a regular expression match:
var string = "bs-00-xyz";
newstring = string.match(/([^-]+-[^-]+)-/i);
// newstring = "bs-00"
This will work for strings with more than two dashes as well.
Example:
var string = "bs-00-xyz-asdf-asd";
I think splitting on character is a fine approach, but just for variety's sake...you could use a regular expression.
var match = yourString.match(/^([^\-]*\-[^\-]*)\-/);
That expression would return the string you're looking for as match[1] (or null if no such string could be found).
you need use lastIndexOf jsfiddle, check this example
link update...

Capturing String Segments between Special Characters using Regular Expressions

I have the following string of text:
textString1:textString2:textString3:textString4
I'm looking to capture each text string and assign them to variables.
I've somehow managed to come up with the following:
var errorText = 'AAAA:BBBB:CCCC:DDDD';
var subString, intro, host, priority, queue = '';
var re = /(.+?\:)/g;
subString = errorText.match(re);
intro = subString[0];
host = subString[1];
priority = subString[2];
//queue = subString[3];
console.log(intro + " " + host + " " + priority);
JS Bin Link
However, I'm having problems with:
capturing the last group, since there is no : at the end
the variables contain : which I'd like to strip
You don't need a regex for this - just use errorText.split(':') to split by a colon. It will return an array.
And if you then want to add them together with spaces, you could do a simple replace instead: errorText.replace(/:/g,' ').
use split method for this.it will return array of string then iterate through array to get string:
var errorText = 'AAAA:BBBB:CCCC:DDDD';
var strArr=errorText.split(':');
console.log(errorText.split(':'));
for(key in strArr){
console.log(strArr[key]);
}

javascript - replacing spaces with a string

I'm new to Javascript and need a bit of help with program on a college course to replace all the spaces in a string with the string "spaces".
I've used the following code but I just can't get it to work:
<html>
<body>
<script type ="text/javascript">
// Program to replace any spaces in a string of text with the word "spaces".
var str = "Visit Micro soft!";
var result = "";
For (var index = 0; index < str.length ; index = index + 1)
{
if (str.charAt(index)= " ")
{
result = result + "space";
}
else
{
result = result + (str.charAt(index));
}
}
document.write(" The answer is " + result );
</script>
</body>
</html>
For
isn't capitalized:
for
and
str.charAt(index)= " "
needs to be:
str.charAt(index) == " "
JavaScript Comparison Operators
for loops
As others have mentioned there are a few obvious errors in your code:
The control flow keyword for must be all lower-case.
The assignment operator = is different than the comparison operators == and ===.
If you are allowed to use library functions then this problem looks like a good fit for the JavaScript String.replace(regex,str) function.
Another option would be to skip the for cycle altogether and use a regular expression:
"Visit Micro soft!".replace(/(\s)/g, '');
Try this:
str.replace(/(\s)/g, "spaces")
Or take a look at this previous answer to a similar question: Fastest method to replace all instances of a character in a string Hope this help
You should use the string replace method. Inconvenienty, there is no replaceAll, but you can replace all anyways using a loop.
Example of replace:
var word = "Hello"
word = word.replace('e', 'r')
alert(word) //word = "Hrllo"
The second tool that will be useful to you is indexOf, which tells you where a string occurs in a string. It returns -1 if the string does not appear.
Example:
var sentence = "StackOverflow is helpful"
alert(sentence.indexOf(' ')) //alerts 13
alert(sentence.indexOf('z')) //alerts -1

Javascript string formatting, short question

How can I use javascript to add a number (any number between 0-100) followed by a underscore, before the variable value?
Example:
2000 becomes 12_2000 //a number of my choice is added followed by an underscore
hello becomes 12_hello
The number (12 in this case) is a constant chosen by me!
Thanks
i + '_' + x where i is the number and x is an arbitrary value.
Just use string concatenation:
var res = '12_' + myNum;
Or with a variable prefix:
var res = prefix + '_' + myNum;
This is just basic string concatenation, which can be done with the + operator:
var num = 2000;
"12_" + num;
// "12_2000"
var_name = "2000";
output = "12_" + var_name;
function prefixWithNumber(value, number) {
return number + "_" + value;
}
This expression is evaluated as (number + "_") + value. Since one of the operants in the first addition is a string literal, the second argument number is converted (coerced) to a string. The result is a string, which causes the third argument to be converted to a string as well.
This is what the JS engine does behind the scenes:
(number.toString() + "_") + value.toString();
Maybe you're looking for something like this:
Object.prototype.addPrefix = function(pre){
return pre + '_' + this;
};
This allows code like:
var a = 5;
alert(a.addPrefix(7));
or even:
"a string".addPrefix(7);
Joining an array can be faster in some cases and more interesting to program than "+"
[i, '_', myNum].join('')

Categories