If I have a string and a number:
var str='Thisisabigstring';
var numb=7;
I'm trying to remove the character at position 'numb' from the string and then put it at the beginning of the string.
Trying for output like:
'aThisisbigstring';
How can I do this with javascript/jquery?
var str = "Thisisabigstring";
var numb=7;
var c = str.charAt(numb);
str = c + str.substr(0, numb) + str.substr(numb + 1);
quick and dirty :)
var b = str.charAt(numb - 1) + str.substring(0, numb - 1) + str.substring(numb);
var s = "Thisisabigstring";
var index = 7;
var x = s.charAt(index) + s.substr(0, (index - 1)) + s.substr(index + 1);
alert(x);
There is no function in javascript which do that. Try this :
String.prototype.replaceCharAt=function(index, char){return this.substr(0, index) + char + this.substr(index+char.length);}
var testStr = your_Test_string;
var CharPosition = Ur_Char_Position;
var pullOutChar = testStr.charAt(CharPosition);
testStr = pullOutChar + str.substr(0, CharPosition) + str.substr(CharPosition + 1);
Sometimes it's easier to convert a string to an Array when doing things like this:
str = str.split('');
str.unshift(str.splice(numb - 1, 1));
str = str.join('');
var x = str.substring(7,8);
str = x + str;
Related
I want an eval() function which will calculate brackets as same as normal calculations but here is my code
var str = "2(3)+2(5)+7(2)+2"
var w = 0;
var output = str.split("").map(function(v, i) {
var x = ""
var m = v.indexOf("(")
if (m == 0) {
x += str[i - 1] * str[i + 1]
}
return x;
}).join("")
console.log(eval(output))
Which takes the string str as input but outputs 61014 and whenever I try evaluating the output string, it remains same.
Obligatory "eval() is evil"
In this case, you can probably parse the input. Something like...
var str = "2(3)+2(5)+7(2)+2";
var out = str.replace(/(\d+)\((\d+)\)/g,(_,a,b)=>+a*b);
console.log(out);
while( out.indexOf("+") > -1) {
out = out.replace(/(\d+)\+(\d+)/g,(_,a,b)=>+a+(+b));
}
console.log(out);
You can do it much simplier, just insert '*' in a right positions before brackets
var str = "2(3)+2(5)+7(2)+2"
var output = str.replace(/\d\(/g, v => v[0] + '*' + v[1])
console.log(eval(output))
Can someone please help me to write a JS method which takes a String value like
/Content/blockDiagram/0/bundle/0/selectedBundle
/Content/blockDiagram/1/bundle/1/selectedBundle
/Content/blockDiagram/0/bundle
and convert it to
/Content/blockDiagram[1]/bundle[1]/selectedBundle
/Content/blockDiagram[2]/bundle[2]/selectedBundle
/Content/blockDiagram[1]/bundle
It is basically taking the number in the path and increment it by 1 and then changing the structure of the string.
My attempt
function setReplicantPartListOptions(list) {
list = "/" + list;
var index = list.lastIndexOf("/");
var tempString = list.substring(0, index);
var index2 = tempString.lastIndexOf("/");
var initialString = list.substring(0, index2);
var result = tempString.substring(index2 + 1, index) var middlevalue = parseFloat(result) + 1
var lastString = list.substring(index, list.length);
list = initialString + "[" + middlevalue + "]" + lastString;
return list;
}
simple regular expression with capture group with replace
var str = "/Content/blockDiagram/0/bundle/0/selectedBundle"
var updated = str.replace(/\/(\d+)/g, function (m, num) {
var next = +num + 1; // convert string to number and add one
return "[" + next + "]"; //return the new string
})
console.log(updated)
String.replace(RegExp, callback(match, contents)) is the callback version of String.replace().
In my case, the first parameter of callback function is the result/match. It takes the match and converts it to number using + operator, and then increment it by one. Finally, I add [ ] around the value and return it!
let str = "/Content/blockDiagram/0/bundle/0/selectedBundle"
console.log(
str.replace(/\b\d+\b/g, match => `[${ +match + 1 }]`)
);
var str = "/Content/blockDiagram/0/bundle/0/selectedBundle"
console.log(
str.replace(/\/(\d+)\//g, function(_,num) { return `[${++num}]`})
)
I'm trying to do this following javascript exercise here:
Create a function called mixUp. It should take in two strings, and return the concatenation of the two strings (separated by a space) slicing out and swapping the first 2 characters of each. You can assume that the strings are at least 2 characters long.
and here's my code:
var mixUP = function(a, b) {
var sliceA = a.slice(0,2);
var sliceAa = a.slice(2);
var sliceB = b.slice(0,2);
var sliceBb = b.slice(2);
var string = sliceA + sliceBb + " " + sliceB + sliceAa;
console.log(string);
};
mixUp(apple, pear);
Could anyone please help me out here coz it's not working for me. Thanks heaps!
The way I approached it was:
function mixUp(stringA, stringB) {
var sliceA = stringA.slice(0,2),
sliceB = stringB.slice(0,2);
return (sliceB + stringA.substring(2) + " " + sliceA +
stringB.substring(2));
}
Which gives you the desired output
If you define mixUP call it, not mixUp last p is uppercase.
When you use strings, you need to add quotes around them:
var mixUp = function (a, b) {
var sliceA = a.slice(0, 2);
var sliceAa = a.slice(2);
var sliceB = b.slice(0, 2);
var sliceBb = b.slice(2);
var string = sliceA + sliceBb + " " + sliceB + sliceAa;
console.log(string);
};
mixUp('apple', 'pear');
OUTPUT
apar peple
Typo's:
mixUp(apple, pear);
should be:
mixUP('apple', 'pear');
^ ^ ^ ^ ^
You called mixUp instead of mixUP, and both apple and pear should be strings (Unless they are variables already)
That'll give you the desired result:
var mixUP = function(a, b) {
var sliceA = a.slice(0,2);
var sliceAa = a.slice(2);
var sliceB = b.slice(0,2);
var sliceBb = b.slice(2);
var string = sliceA + sliceBb + " " + sliceB + sliceAa;
console.log(string);
};
mixUP('apple', 'pear');
Either change the function calling or the function definition to same name as you have taken different names for both.
var mixUP = function(a, b) {
var sliceA = a.slice(0,2);
var sliceAa = a.slice(2);
var sliceB = b.slice(0,2);
var sliceBb = b.slice(2);
var string = sliceA + sliceBb + " " + sliceB + sliceAa;
console.log(string);
};
mixUP("apple", "pear"); // apar peple
Without using the split reverse and join functions, how would one do such a thing?
The Problem Given: Reverse the words in a string
Sample Input: "Hello World"
Sample Output: "World Hello"
<script>
var newString = "";
var theString = prompt("Enter a Phrase that you would like to reverse (Ex. Hello world)");
newString = theString.split(" ").reverse().join(" ")
document.write(newString);
</script>
Arrays can be used like stacks out of the box. And stacks are LIFO, which is what you need.
function reverseWords(str) {
var word, words, reverse;
words = str.match(/(?:\w+)/g);
reverse = '';
while(word = words.pop()) {
reverse += word + ' ';
}
return reverse.trim();
}
reverseWords('hello world');
Or use the call stack as your stack:
function reverseWords(str) {
var result = '';
(function readWord(i = 0) {
var word = '';
if(i > str.length) {
return '';
}
while(str[i] !== ' ' && i < str.length) {
word += str[i];
i++;
}
readWord(++i); // Skip over delimiter.
result += word + ' ';
}());
return result.trim();
}
reverseWords('hello world');
Another idea for reversing the words in a String is using a Stack data structure. Like so:
var newString = "";
var theString = prompt("Enter a Phrase that you would like to reverse (Ex. Hello world)");
var word = "";
var c;
var stack = [];
for (var i = 0, len = theString.length; i < len; i++) {
c = theString[i];
word += c;
if (c == " " || i == (len-1)) {
word = word.trim();
stack.push(word);
word = "";
}
}
while (s = stack.pop()) {
newString += s + " ";
}
console.log(newString);
You could also go fancy and try something like this:
I couldn't come up with a shorter solution.
var newString = "";
var theString = prompt("Enter a Phrase that you would like to reverse (Ex. Hello world)");
theString.replace(/[^\s]*/g, function (value) {
newString = value + ' ' + newString;
});
document.write(newString);
Of the millions of different solutions, the least amount of typing I could come up with involves using lastIndexOf and substring.
var str = "The quick brown fox",
reversed = "",
idx;
while(true) {
idx = str.lastIndexOf(" ")
reversed = reversed + str.substring(idx).trim() + " "
if (idx < 0) break;
str = str.substring(0, idx)
}
reversed.trim() # Oh, yes, trim too
Output:
"fox brown quick The"
The simplest way to do in javascript. Here replace() have /,/g it will replace all comma from the string to space.
var msg = 'Hello world I am Programmer';
var newstr = msg.split(" ").reverse().join().replace(/,/g, ' ');
console.log(newstr)
;
I have a sting like this:
"a;b;x"
and I want to convert it to
"a"; "b"; "x"
You can use map to to return an array that you join at the end of the operation.
The map operation merely checks to see if the current element is the last in the array. If it is, don't append a semi-colon, then return the transformed element.
var output = str.split(';').map(function (el, i, arr) {
return i === (arr.length - 1) ? '"' + el + '"' : '"' + el + '";'
}).join(' ');
DEMO
Or perhaps the slightly easier to understand:
var output = str.split(';').map(function (el, i, arr) {
var end = i === (arr.length - 1) ? '' : ';';
return '"' + el + '"' + end;
}).join(' ');
you are searching for split() method
http://www.w3schools.com/jsref/jsref_split.asp
var str = "a;b;x";
var str_split = str.split(";");
var result = '"';
for (var i = 0; i < str_split.length; i++) {
result += str_split[i] + '"; "' }
result = result.substring(0, result.length - 3);
have a nice day ;)
This regexp wraps each letter by quote symbol and adding space symbol with new ";".And removes from end last "; "
var result = "a;b;x".replace(/(\w)(;)*/g,'"$1"; ').replace(/;\s+$/g,"");
console.log(result) // '"a"; "b"; "x"'
$1 - is letter