Jump to content

So I have googled this and read the MDN page about it. 

It says the syntax goes something like this: 

 

string.replace(regexp/substr, newSubStr/function[, flags]);

this kind of confuses me, should I understand it in these ways? 

 

  • string.replace(old things, new things)    // old things are being replaced with new things 
  • if so, does this code snippet work?? why or why not?? 
var string = "this is a test! ";
string.replace(t,T);
  • what does // do?? and what about the i? 
var str = 'Twas the night before Xmas...';
var newstr = str.replace(/xmas/i, 'Christmas');
console.log(newstr);  // Twas the night before Christmas...

 

 

im really confused with the syntax with this. 

could someone give me some examples of how to do this and what are the practical uses of this replace method in real life? 

If it is not broken, let's fix till it is. 

Link to comment
https://linustechtips.com/topic/932683-stringreplace-in-javascript/
Share on other sites

Link to post
Share on other sites

str. This is the string you want to effect

replace(What to replace, what to replace it with)

 

Uses removing white space, 

 

const name = 'vorticalbox            ';

const clean = name.replace(' ','')

// clean is now 'vorticalbox'

 

Or you might want to remove all numbers

 


const name = 'vorticalbox123 ';

const clean = name.replace(/\d/gi, '')

// clean is now 'vorticalbox'

                     ¸„»°'´¸„»°'´ Vorticalbox `'°«„¸`'°«„¸
`'°«„¸¸„»°'´¸„»°'´`'°«„¸Scientia Potentia est  ¸„»°'´`'°«„¸`'°«„¸¸„»°'´

Link to post
Share on other sites

@mrchow19910319 

task is to get a list of all the items in an object but not the items inside the array of items.

 

https://repl.it/@vorticalbox/FreshValidRelationalmodel

 

 

const getObjectKeys = (obj, prefix = '') => {
    // console.debug(`Input object: ${JSON.stringify(obj)}`);
    let keys = Object.keys(obj).reduce((res, el) => {
        // console.debug(`Iteration: ${JSON.stringify(res)} ${JSON.stringify(el)}`);
        if (obj[el] !== null && typeof (obj[el]) === 'object') {
            return [...res, ...getObjectKeys(obj[el], `${prefix + el}.`)];
        }
        return [...res, prefix + el];
    }, []);
    keys = keys.map((ei) => {
      //removes the 0 of the array from the list
        let tmp = ei.replace(/\.[0-9]+/, '');
      	//removes the name from array items
        tmp = tmp.replace(/\.name/, '');             
        return tmp;
    });
    keys = keys.filter((item, pos) => {
        // console.debug(`item pos ${item} ${pos}`);
        return keys.indexOf(item) == pos;
    });
    return keys;
};

const data = {
  form: {
    items: [
      {name: 'item'},
      {name: 'item'}
    ],
    user: 'user',
  }
}
console.log(getObjectKeys(data))

output

 


[ 'form.items', 'form.user' ]
	

                     ¸„»°'´¸„»°'´ Vorticalbox `'°«„¸`'°«„¸
`'°«„¸¸„»°'´¸„»°'´`'°«„¸Scientia Potentia est  ¸„»°'´`'°«„¸`'°«„¸¸„»°'´

Link to post
Share on other sites

9 hours ago, mrchow19910319 said:

string.replace(old things, new things)

Yes, this is correct.

 

 

9 hours ago, mrchow19910319 said:
  • if so, does this code snippet work?? why or why not?? 

var string = "this is a test! ";
string.replace(t,T);

In your example, t and T are variables as they are not in "" as so this will error. Try:

var s = "this is a test! ";
s.replace("t", "T")
// "This is a test! "

(Note: only the first t is capitalized)

 

9 hours ago, mrchow19910319 said:
  • what does // do?? and what about the i? 

var str = 'Twas the night before Xmas...';
var newstr = str.replace(/xmas/i, 'Christmas');
console.log(newstr);  // Twas the night before Christmas...

the /xx/ is a RegExp object (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp) and the "i" makes it case insensitive.

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×